如何从数据框中获取列的所有可能组合? [英] How to get all possible combination of column from the data frame?

查看:78
本文介绍了如何从数据框中获取列的所有可能组合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我想通过R包从数据框中获取所有可能的列组合吗?时间越少越好

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

结果看起来像这样

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
...

推荐答案

我已经创建了一个函数,可以在需要时使用:

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...

该函数输出一个列表,其中每个元素是具有所有2向,3向,4向...组合的另一个列表.在您的情况下,它有9个元素,从2向组合一直到10向组合.

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.

这篇关于如何从数据框中获取列的所有可能组合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆