Processing nested lists in nested for loop

54 views Asked by At

I have 2 variables, and I need to create all combinations using these 2 variables. I have been able to achieve this using R combn function, and finally store the combinations within a nested list. Now I need to run some calculation for each combination and store the combined output together. I am trying to store the output in a list but for some reason the output list is not being generated the correct way. Below is an example code:

''''
input_variables <- c("a","b") 
         output_sublist <- list() 
         output_biglist <- list()
         input_combination_list <- list()

         for (i in 1:length(input_variables)) {
           input_combination_list[[i]] <- combn(input_variables, i, simplify = FALSE)
           for(j in 1:length(input_combination_list[[i]]))  {
             input_combination_list[[i]][[j]]
             output_sublist[[j]] <-  input_combination_list[[i]][[j]]
           }
           output_biglist[[i]] <- output_sublist
         }''''

The output that I get is:

[[1]]
[[1]][[1]]
[1] "a"

[[1]][[2]]
[1] "b"


[[2]]
[[2]][[1]]
[1] "a" "b"

[[2]][[2]]
[1] "b"

What I would like to have is:

[[1]]
[[1]][[1]]
[1] "a"

[[1]][[2]]
[1] "b"


[[2]]
[[2]][[1]]
[1] "a" "b"

I am not sure why there is an extra "b" in the end!! Any help would be greatly appreciated. Thanks a lot in advance.

1

There are 1 answers

1
Ronak Shah On BEST ANSWER

output_sublist for i = 1 is

#[[1]]
#[1] "a"

#[[2]]
#[1] "b"

For i = 2, since we don't clear output_sublist it replaces only the first value and second value remains as it is.

#[[1]]
#[1] "a" "b"

#[[2]]
#[1] "b"

You need to clear output_sublist after each iteration of i.

for (i in 1:length(input_variables)) {
   output_sublist <- list() #Added a line here to clear output_sublist
   input_combination_list[[i]] <- combn(input_variables, i, simplify = FALSE)
   for(j in 1:length(input_combination_list[[i]]))  {
      input_combination_list[[i]][[j]]
      output_sublist[[j]] <-  input_combination_list[[i]][[j]]
    }
    output_biglist[[i]] <- output_sublist
}

output_biglist
#[[1]]
#[[1]][[1]]
#[1] "a"

#[[1]][[2]]
#[1] "b"


#[[2]]
#[[2]][[1]]
#[1] "a" "b"

However, as mentioned in the comments we can do this with lapply as well

lapply(seq_along(input_variables), function(x) 
         combn(input_variables, x, simplify = FALSE))

#[[1]]
#[[1]][[1]]
#[1] "a"

#[[1]][[2]]
#[1] "b"


#[[2]]
#[[2]][[1]]
#[1] "a" "b"