Home > front end >  how to generate without repeating the combination in R using the function combn() and generalize the
how to generate without repeating the combination in R using the function combn() and generalize the

Time:09-27

Hy, I have this:

list(
myvector_a=c("X1","X2","X3"),
myvector_b=c("X1","X3","X4"),
myvector_c=c("X2","X5","X6"))->mydata

Expected output: build manually

list(
  myvector_a=list(c_1_1=myvector_a[[1]],
                  c_1_2=myvector_a[[2]],
                  c_1_3=myvector_a[[3]],
                  c_2_1=c(myvector_a[[1]],myvector_a[[2]]),
                  c_2_1=c(myvector_a[[1]],myvector_a[[3]]),
                  c_2_1=c(myvector_a[[2]],myvector_a[[3]]),
                  c_3_1=c(myvector_a[[1]],myvector_a[[2]],myvector_a[[3]])),
  myvector_b=list(c_1_1=myvector_b[[1]],
                  c_1_2=myvector_b[[2]],
                  c_1_3=myvector_b[[3]],
                  c_2_1=c(myvector_b[[1]],myvector_b[[2]]),
                  c_2_1=c(myvector_b[[1]],myvector_b[[3]]),
                  c_2_1=c(myvector_b[[2]],myvector_b[[3]]),
                  c_3_1=c(myvector_b[[1]],myvector_b[[2]],myvector_b[[3]])),
  myvector_c=list(c_1_1=myvector_c[[1]],
                  c_1_2=myvector_c[[2]],
                  c_2_1=c(myvector_c[[1]],myvector_c[[2]])))->result

This was my closest solution to what I need:

x<-NULL
for(i in 1:3)
  for(j in 1:length(mydata[[i]]))
    combn(mydata[[i]],j) -> result[[paste0(names(mydata[i]))]][[paste0("c_",i,"_",j)]]

For example, in Output obtained: result[["myvector_a"]][["c_1_2"]] I couldn't separate as in Expected output: result[["myvector_a"]][["c_2_1"]], result[["myvector_a "]][["c_2_2"]] and result[["myvector_a"]][["c_2_3"]].

Expected output:                                                                     Output obtained: enter image description here

CodePudding user response:

Here's a way using lapply within lapply -

result <- lapply(mydata, function(x) {
  unlist(lapply(seq_along(x), function(y) combn(x, y, list)), recursive = FALSE)
})

enter image description here


Using list and unlist is done only to get the required structure of the output. If you are not too concerned about it this would work as well.

result <- lapply(mydata, function(x) lapply(seq_along(x), function(y) combn(x, y)))
  • Related