rcombinationscombn

Create combination of all elements in a list


I am creating a function that requires the user to enter the input variables and then the function creates all possible combinations (of varying lengths) of those input parameters. Lets say input variables are "A", "B", and "C".

Combination # Input1 Input2 Input3
1 A B C
2 A B
3 A
4 B C
5 B
6 A C
7 C

I want R to form all possible combinations of A, B, and C and create a data frame for it. For example:

Any idea how I can achieve this? Thanks!


Solution

  • You may try

    library(dplyr)
    
    x <- c(TRUE,FALSE)
    
    expand.grid(x,x,x) %>%
      filter(rowSums(.) != 0) %>%
      mutate(Var1 = ifelse(Var1, "A", ""),
             Var2 = ifelse(Var2, "B", ""),
             Var3 = ifelse(Var3, "C", "")) %>%
      tibble::rownames_to_column()
    
      rowname Var1 Var2 Var3
    1       1    A    B    C
    2       2         B    C
    3       3    A         C
    4       4              C
    5       5    A    B     
    6       6         B     
    7       7    A          
    

    function

    func <- function(input){
      n <- length(input)
      x <- c(TRUE,FALSE)
      
      y <- expand.grid(rep(list(x),n)) %>%
        filter(rowSums(.) != 0)
      
      for (i in 1:length(input)){
        y[,i] [y[,i]] <- input[i]
        y[,i][y[,i] != input[i]] <- ""
        
      }
      
      y %>%
        rownames_to_column()
    }
    
    
    inp <- c("A", "B", "C")
    func(inp) 
    
      rowname Var1 Var2 Var3
    1       1    A    B    C
    2       2         B    C
    3       3    A         C
    4       4              C
    5       5    A    B     
    6       6         B     
    7       7    A