How to get all possible combination of column from the data frame?

前端 未结 1 795
广开言路
广开言路 2020-12-12 03:12
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>         


        
相关标签:
1条回答
  • 2020-12-12 03:56

    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.

    0 讨论(0)
提交回复
热议问题