简体   繁体   中英

Building all combinations of a vector - looking for a nicer way

I have a simple case which I could solve in an ugly way, but I am sure a much cleverer (and faster) way must exist.

Let's take this vector

d <- 1:6

I want to list all the possible combinations in a "going-forward" way :

1 2
1 3
1 4
1 5
1 6
2 3
2 4
2 5
...
5 6

The working way I could first come with is the following

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)
}

I am sure there must be a cleverer way to doing that.

Loud debugging? I just found this way

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

One approach using expand.grid and subsetting:

d <- 1:6

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

This may not be the best way to go about things if you have large vectors and memory constraints as the expand.grid call generates a lot of items that are removed, but it is quite readable and communicates intent clearly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM