R 构建向量的所有组合-寻找更好的方法

R 构建向量的所有组合-寻找更好的方法,r,R,我有一个简单的案例,我可以用一种丑陋的方式来解决,但我相信一定存在一种更聪明(更快)的方式 让我们用这个向量 d <- 1:6 我首先可以采用的工作方式如下 n <- 6 combDF <- data.frame() for( i in 1:(n-1)){ thisVal <- rep(i,n-i) nextVal <- cumsum(rep(1,n-1)) + 1 nextVal <- nextVal[nextVal > i] p

我有一个简单的案例,我可以用一种丑陋的方式来解决,但我相信一定存在一种更聪明(更快)的方式

让我们用这个向量

d <- 1:6
我首先可以采用的工作方式如下

n <- 6
combDF <- data.frame()
for( i in 1:(n-1)){

  thisVal <- rep(i,n-i)
  nextVal <- cumsum(rep(1,n-1)) +  1
  nextVal <- nextVal[nextVal > i]
  print("---")
  print(thisVal)
  print(nextVal[nextVal > i])
 df <- data.frame(thisVal = thisVal, nextVal = nextVal)
 combDF <- rbind(combDF, df)
}

n大声调试?我刚找到这条路

as.data.frame(t(combn(d,m=2)))

  V1 V2
1   1  2
2   1  3
3   1  4
4   1  5
5   1  6
6   2  3
7   2  4
8   2  5
9   2  6
10  3  4
11  3  5
12  3  6
13  4  5
14  4  6
15  5  6

一种使用
expand.grid
和子集的方法:

d <- 1:6

foo <- expand.grid(a = d, b = d)
foo[foo[, "a"] > foo[, "b"], c("b", "a")]

d我更喜欢这种方法!很好添加更多的基本R函数到我的vocab。。。
d <- 1:6

foo <- expand.grid(a = d, b = d)
foo[foo[, "a"] > foo[, "b"], c("b", "a")]