How to get all possible combination of column from

2020-02-07 06:13发布

R> set.seed(123)
R> data <- matrix(rnorm(6),3,10)
R> colnames(data) <- c("s1","s2","s3","s4","s5","s6","s7","s8","s9","s10")
R> print(data)

sorry, I don't know how to show the print

I would like to get all possible combination of column from the data frame by R package? Less time is better

The result look like this,

All possible two pair combination
column S1 and S2
column S2 and S3
column S3 and S4
...

all possible three pair combination
column S1, S2 and S3
column S2, S3 and S4
column S3, S4 and S5
...

1条回答
别忘想泡老子
2楼-- · 2020-02-07 06:57

I have made a function to do this which comes in handy whenever I need it:

make_combinations <- function(x) {

  l <- length(x)
  mylist <- lapply(2:l, function(y) {
    combn(x, y, simplify = FALSE)
  })
  mylist

}


results <- make_combinations(colnames(data))
results[[1]]
# [[1]]
# [1] "s1" "s2"
# 
# [[2]]
# [1] "s1" "s3"
# 
# [[3]]
# [1] "s1" "s4"
# 
# [[4]]
# [1] "s1" "s5"
# 
# [[5]]
# [1] "s1" "s6"
# 
# [[6]]
# [1] "s1" "s7"
#and so on...

The function outputs a list, where each element is another list with all the 2-way, 3-way, 4-way... combinations. In your case it has 9 elements starting from the 2-way combinations all the way to the 10-way combination.

查看更多
登录 后发表回答