Home > Software engineering >  Adding elements of combinations of vector in a list in R
Adding elements of combinations of vector in a list in R

Time:10-06

I am pretty new in R and so what I am trying to do is that I have been given a vector of positive integers like

index <- 1:3

and I want to use this vector to find all the possible combinations of numbers without repetition which I achieve like this

for (i in 1:length(index)) {
 combn(index,i)
 j = 1
 while (j <= nrow(t(combn(index,i)))) {
     print(t(combn(index,i))[j,])
     j = j   1
     append(comb, j)
 }
 }

This gives me output as

[1] 1
[1] 2
[1] 3
[1] 1 2
[1] 1 3
[1] 2 3
[1] 1 2 3

But when I create a list comb <- list() and try to append each output as below:

for (i in 1:length(index)) {
combn(index,i)
j = 1
while (j <= nrow(t(combn(index,i)))) {
    append(comb, t(combn(index,i))[j,])
    j = j   1
}
}

The problem is it is giving my empty list when I call

comb
list()

I wish to create a list with those elements and use them to retrieve those index rows from a data frame. Do you have any idea how I can achieve this? Any help is welcome. Thanks!

CodePudding user response:

We can use unlist lapply like below

unlist(
  lapply(
    seq_along(index),
    combn,
    x = index,
    simplify = FALSE
  ),
  recursive = FALSE
)

which gives

[[1]]
[1] 1

[[2]]
[1] 2

[[3]]
[1] 3

[[4]]
[1] 1 2

[[5]]
[1] 1 3

[[6]]
[1] 2 3

[[7]]
[1] 1 2 3

CodePudding user response:

This seems to give what you want

index <- 1:3

comb <- list()

for (i in 1:length(index)) {
  combn(index,i)
  j = 1
  while (j <= nrow(t(combn(index,i)))) {
    comb <- c(comb, list(t(combn(index,i))[j,]))
    j = j   1
  }
}

comb

Output

[[1]]
[1] 1

[[2]]
[1] 2

[[3]]
[1] 3

[[4]]
[1] 1 2

[[5]]
[1] 1 3

[[6]]
[1] 2 3

[[7]]
[1] 1 2 3

Note that you have to assign your appended list back. Also if you append a list with vector each of the vector element will be a separate element in the new list. You have to wrap that vector in a list() function to append it as one.

  • Related