0

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!

neilfws
  • 32,751
  • 5
  • 50
  • 63
kav
  • 85
  • 6
  • Possible duplicates - https://stackoverflow.com/questions/27953588/unordered-combinations-of-all-lengths/49591309 or https://stackoverflow.com/questions/17817897/all-combinations-of-all-sizes – thelatemail Nov 22 '21 at 04:13

1 Answers1

1

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          
Park
  • 14,771
  • 6
  • 10
  • 29
  • Your question assumes that only 3 input variables are given. I am trying to create a function for n-input variables. Any idea how I can develop the function for any number of input variables? Thanks for the input! – kav Nov 22 '21 at 04:16
  • 1
    @kav I add generalized function version. – Park Nov 22 '21 at 04:28
  • @kav I did a little update to function that removed input `n`. It wasn't needed in function. Sorry for confusing. – Park Nov 22 '21 at 04:32