Home > Back-end >  How to assign a list within list in a for loop in R
How to assign a list within list in a for loop in R

Time:01-28

I am trying to figure out why, methodologically, my code below is not working.

formatted_data is a list containing 20 different data frames with various columns. ff_demog_table is a function that formats the data frames within formatted_data. Finally, formatted_tables should be a list saving the different formatted data frames.

I want to iterate over each data frame in the formatted_data list, and then iterate over each column within each data frame. It seems like I am not able to directly assign formatted_tables as [[i]][[j]] but it will display the last formatted column if I use just formatted_tables[[i]].

For example, if I try to run the code below, the subscript is out of bounds. Why?

a <- list()
a[[1]][[1]] <- 7

But, if I ran the code below it will work.

b <- list()
b[[1]] <- 7
b[[1]][[1]] <- 8

I am not able to share the data, but a simple reproducible example would be merely two data frames with multiple columns saved in a list where the columns are made up of factors.

for (i in seq_along(formatted_data)) {
  
  for (j in 1:ncol(formatted_data[[i]])) {
    
    formatted_tables[[i]][[j]] <- ff_demog_table(formatted_data[[i]], colnames(formatted_data[[i]][j]))
    
  }
  
}

In short, any help on understanding R's list indexing would be very helpful. Thank you!

CodePudding user response:

We may initialize the list with a specific length. In the below code, it is a list of length 1 instead of the 0 length list with list()

a <- vector('list', 1)
a[[1]][[1]] <- 7

Or if we want to construct from length 0 list, wrap with list on the rhs of <-

a <- list()
a[1] <- list(list(7))

-output structure

> str(a)
List of 1
 $ :List of 1
  ..$ : num 7
  •  Tags:  
  • Related