There's another way to assign to a list, using my_list[[name or number]] <-. If you really want to do that in a loop, just looping over things with names like iter1, iter2, ...

A <- list()
n_iter <- 2
for (i in 1:n_iter){
    iname <- paste("iter",i,sep="")
    A[[iname]] <- get(iname)
}

As @mnel pointed out, dynamically growing a list is inefficient. The alternative is, I think, to use lapply:

n_iter <- 2
inames <- paste("iter",1:n_iter,sep="")
names(inames) <- inames
A <- lapply(inames,get)

This can also be done with a data frame, which would be a better format if your sublists always have two elements, each having a consistent class (item1 being numeric and item 2 being character).

n_iter <- 2
DF <- data.frame(item1=rep(0,n_iter),item2=rep("",n_iter),stringsAsFactors=FALSE)
for (i in 1:n_iter){
     iname <- paste("iter",i,sep="")
     DF[i,] <- get(iname)
     rownames(DF)[i] <- iname
}

#       item1 item2
# iter1     1     a
# iter2     1     b

However, that's a pretty ugly way of doing things; things get messy pretty quickly when using get. With your data structure, maybe you want to create iter1 and iter2 in a loop and immediately embed them into the parent list or data frame?

n_iter = 10
DF <- data.frame(item1 = rep(0,n_iter), item2 = rep("",n_iter))
for (i in 1:n_iter){
    ... do stuff to make anum and achar ...
    DF[i,"item1"] <- anum
    DF[i,"item2"] <- achar
}

Where anum and achar are the values of item1 and item2 you want to store from that iteration. Elsewhere on SO, they say that there is an alternative using the data.table package that is almost 10x as fast/efficient as this sort of data-frame assignment.

Oh, one last idea: if you want to put them in a list first, you can easily convert to a data frame later with

DF <- do.call(rbind.data.frame,A)
Answer from Frank on Stack Overflow
Top answer
1 of 4
10

There's another way to assign to a list, using my_list[[name or number]] <-. If you really want to do that in a loop, just looping over things with names like iter1, iter2, ...

A <- list()
n_iter <- 2
for (i in 1:n_iter){
    iname <- paste("iter",i,sep="")
    A[[iname]] <- get(iname)
}

As @mnel pointed out, dynamically growing a list is inefficient. The alternative is, I think, to use lapply:

n_iter <- 2
inames <- paste("iter",1:n_iter,sep="")
names(inames) <- inames
A <- lapply(inames,get)

This can also be done with a data frame, which would be a better format if your sublists always have two elements, each having a consistent class (item1 being numeric and item 2 being character).

n_iter <- 2
DF <- data.frame(item1=rep(0,n_iter),item2=rep("",n_iter),stringsAsFactors=FALSE)
for (i in 1:n_iter){
     iname <- paste("iter",i,sep="")
     DF[i,] <- get(iname)
     rownames(DF)[i] <- iname
}

#       item1 item2
# iter1     1     a
# iter2     1     b

However, that's a pretty ugly way of doing things; things get messy pretty quickly when using get. With your data structure, maybe you want to create iter1 and iter2 in a loop and immediately embed them into the parent list or data frame?

n_iter = 10
DF <- data.frame(item1 = rep(0,n_iter), item2 = rep("",n_iter))
for (i in 1:n_iter){
    ... do stuff to make anum and achar ...
    DF[i,"item1"] <- anum
    DF[i,"item2"] <- achar
}

Where anum and achar are the values of item1 and item2 you want to store from that iteration. Elsewhere on SO, they say that there is an alternative using the data.table package that is almost 10x as fast/efficient as this sort of data-frame assignment.

Oh, one last idea: if you want to put them in a list first, you can easily convert to a data frame later with

DF <- do.call(rbind.data.frame,A)
2 of 4
5

This gets you the equivalent of your All

c(iter1=list(iter1), iter2=list(iter2))

> identical(c(iter1=list(iter1), iter2=list(iter2)), All)
[1] TRUE

Let's say you'd like to add a third list to All:

c(All, list(iter3=iter3))

If you don't care for the list names, it looks a little cleaner

 c(list(iter1), list(iter2))
🌐
Statistics Globe
statisticsglobe.com › home › learn r programming (tutorial & examples) | free introduction › create nested list in r (2 examples)
Create Nested List in R (2 Examples) | Build List of Lists in for-Loop
March 21, 2022 - The following R programming code shows how to merge multiple list objects in a nested list using the list() function in R. For this, we simply have to specify the names of our lists separated by a comma within the list function:
Discussions

Working with nested lists
if you're working with nested lists, you could look into how JSON documents are converted to data frames in R and use similar techniques. JSON documents are usually represented as nested lists in R - you'll need to flatten the lists out and then you could probably use rbindlists() to join them all together. Sorry if this doesn't apply exactly, but maybe it gives you a direction. More on reddit.com
🌐 r/rstats
17
2
May 26, 2021
tidyr - accessing nested lists in R - Stack Overflow
An alternative way to pull out ... aren't working with a list. This would avoid the need to flatten later. asia = nest_2 %>% filter(continent == "Asia") %>% select(by_continent) %>% unnest ... I don't use purrr so don't quite understand how you ended up with something this weird/deeply nested (it seems you're following ... More on stackoverflow.com
🌐 stackoverflow.com
How can I access data in a nested R list? - Stack Overflow
Connect and share knowledge within a single location that is structured and easy to search. Learn more about Teams ... I want to learn how to access data from a nested list in R. I am relatively new to the R programming language, so I am unsure how to proceed. More on stackoverflow.com
🌐 stackoverflow.com
How to efficiently manipulate the contents of nested lists in R - Stack Overflow
View results. Find centralized, trusted content and collaborate around the technologies you use most. Learn more about Collectives ... Connect and share knowledge within a single location that is structured and easy to search. Learn more about Teams ... I am currently working with nested lists ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
UC Business Analytics
uc-r.github.io › lists
Managing Lists · UC Business Analytics R Programming Guide
# preserve the output as a list l3[[2]][1] ## $item2a ## [1] "a" "b" "c" "d" "e" # same as above but simplify the output l3[[2]][[1]] ## [1] "a" "b" "c" "d" "e" # same as above with names l3[["item2"]][["item2a"]] ## [1] "a" "b" "c" "d" "e" # same as above with `$` operator l3$item2$item2a ## [1] "a" "b" "c" "d" "e" # extract individual element from a nested list item l3[[2]][[1]][3] ## [1] "c" Install and load the nycflights13 package. Using the flights data provided by this package create the following regression model:
🌐
Tender Is The Byte
tenderisthebyte.com › blog › 2019 › 11 › 02 › notes-from-the-messyverse-tidying-nested-lists
Notes from the Messyverse: How to tidy nested lists in R | Tender Is The Byte
November 2, 2019 - Since you want each of the nested lists to be a row in your data frame, you’ll need map_dfr. But what kind of function to you need to apply to each of the lists? It turns out that you need a function that returns its argument as is, somthing like function(l) l. You give that a try. > experiment_a %>% map_dfr(function(l) l) # A tibble: 4 x 2 group weight <chr> <dbl> 1 Control 10 2 Control 8 3 Treatment 15 4 Treatment 14 · Hey that worked...
🌐
tidyr
tidyr.tidyverse.org › articles › nest.html
Nested data • tidyr
mtcars_nested <- mtcars_nested |> mutate(pred = map(model, predict)) mtcars_nested #> # A tibble: 3 × 4 #> # Groups: cyl [3] #> cyl data model pred #> <dbl> <list> <list> <list> #> 1 6 <tibble [7 × 10]> <lm> <dbl [7]> #> 2 4 <tibble [11 × 10]> <lm> <dbl [11]> #> 3 8 <tibble [14 × 10]> <lm> <dbl [14]> This workflow works particularly well in conjunction with broom, which makes it easy to turn models into tidy data frames which can then be unnest()ed to get back to flat data frames.
🌐
Reddit
reddit.com › r/rstats › working with nested lists
r/rstats on Reddit: Working with nested lists
May 26, 2021 -

Hi, I'm having a tough time trying to work with lists. I'm getting data from an API (nhlapi) and its a nested list of lists ...

I want to transform those lists into data frames, but even at the lowest level some items differ in length so functions like rbind/bind_row doesn't work. I tried using purrr, but I'm struggling.

Do you guys know any material that teaches how to work with lists? I tried looking on youtube but only found some very basic stuff. I would post the list structure but its too big to even fit in the console. Any help would be highly appreciated. Thanks

Edit: so I'm will be trying to use unnest function of the tidyr package and see what that will do. I'll post here too, the dump of str() function:

List of 1
 $ :List of 3
  ..$ copyright: chr "NHL and the NHL Shield are registered trademarks of the National Hockey League. NHL and NHL team marks are the "| __truncated__
  ..$ teams    :List of 2
  .. ..$ away:List of 10
  .. .. ..$ team      :List of 3
  .. .. .. ..$ id  : int 10
  .. .. .. ..$ name: chr "Toronto Maple Leafs"
  .. .. .. ..$ link: chr "/api/v1/teams/10"
  .. .. ..$ teamStats :List of 1
  .. .. .. ..$ teamSkaterStats:List of 11
  .. .. .. .. ..$ goals                 : int 4
  .. .. .. .. ..$ pim                   : int 8
  .. .. .. .. ..$ shots                 : int 28
  .. .. .. .. .. [list output truncated]
  .. .. ..$ players   :List of 37
  .. .. .. ..$ ID8475718:List of 4
  .. .. .. .. ..$ person      :List of 22
  .. .. .. .. .. ..$ id                : int 8475718
  .. .. .. .. .. ..$ fullName          : chr "Justin Holl"
  .. .. .. .. .. ..$ link              : chr "/api/v1/people/8475718"
  .. .. .. .. .. .. [list output truncated]
  .. .. .. .. ..$ jerseyNumber: chr "3"
  .. .. .. .. ..$ position    :List of 4
  .. .. .. .. .. ..$ code        : chr "D"
  .. .. .. .. .. ..$ name        : chr "Defenseman"
  .. .. .. .. .. ..$ type        : chr "Defenseman"
  .. .. .. .. .. .. [list output truncated]
  .. .. .. .. .. [list output truncated]
  .. .. .. ..$ ID8477939:List of 4
  .. .. .. .. ..$ person      :List of 22
  .. .. .. .. .. ..$ id                : int 8477939
  .. .. .. .. .. ..$ fullName          : chr "William Nylander"
  .. .. .. .. .. ..$ link              : chr "/api/v1/people/8477939"
  .. .. .. .. .. .. [list output truncated]
  .. .. .. .. ..$ jerseyNumber: chr "88"
  .. .. .. .. ..$ position    :List of 4
  .. .. .. .. .. ..$ code        : chr "R"
  .. .. .. .. .. ..$ name        : chr "Right Wing"
  .. .. .. .. .. ..$ type        : chr "Forward"
  .. .. .. .. .. .. [list output truncated]
  .. .. .. .. .. [list output truncated]
  .. .. .. ..$ ID8478408:List of 4
  .. .. .. .. ..$ person      :List of 22
  .. .. .. .. .. ..$ id                : int 8478408
  .. .. .. .. .. ..$ fullName          : chr "Travis Dermott"
  .. .. .. .. .. ..$ link              : chr "/api/v1/people/8478408"
  .. .. .. .. .. .. [list output truncated]
  .. .. .. .. ..$ jerseyNumber: chr "23"
  .. .. .. .. ..$ position    :List of 4
  .. .. .. .. .. ..$ code        : chr "D"
  .. .. .. .. .. ..$ name        : chr "Defenseman"
  .. .. .. .. .. ..$ type        : chr "Defenseman"
  .. .. .. .. .. .. [list output truncated]
  .. .. .. .. .. [list output truncated]
  .. .. .. .. [list output truncated]
  .. .. .. [list output truncated]
  .. ..$ home:List of 10
  .. .. ..$ team      :List of 3
  .. .. .. ..$ id  : int 8
  .. .. .. ..$ name: chr "Montréal Canadiens"
  .. .. .. ..$ link: chr "/api/v1/teams/8"
  .. .. ..$ teamStats :List of 1
  .. .. .. ..$ teamSkaterStats:List of 11
  .. .. .. .. ..$ goals                 : int 0
  .. .. .. .. ..$ pim                   : int 4
  .. .. .. .. ..$ shots                 : int 32
  .. .. .. .. .. [list output truncated]
  .. .. ..$ players   :List of 34
  .. .. .. ..$ ID8480051:List of 4
  .. .. .. .. ..$ person      :List of 22
  .. .. .. .. .. ..$ id                : int 8480051
  .. .. .. .. .. ..$ fullName          : chr "Cayden Primeau"
  .. .. .. .. .. ..$ link              : chr "/api/v1/people/8480051"
  .. .. .. .. .. .. [list output truncated]
  .. .. .. .. ..$ jerseyNumber: chr "30"
  .. .. .. .. ..$ position    :List of 4
  .. .. .. .. .. ..$ code        : chr "N/A"
  .. .. .. .. .. ..$ name        : chr "Unknown"
  .. .. .. .. .. ..$ type        : chr "Unknown"
  .. .. .. .. .. .. [list output truncated]
  .. .. .. .. .. [list output truncated]
  .. .. .. ..$ ID8480829:List of 4
  .. .. .. .. ..$ person      :List of 21
  .. .. .. .. .. ..$ id              : int 8480829
  .. .. .. .. .. ..$ fullName        : chr "Jesperi Kotkaniemi"
  .. .. .. .. .. ..$ link            : chr "/api/v1/people/8480829"
  .. .. .. .. .. .. [list output truncated]
  .. .. .. .. ..$ jerseyNumber: chr "15"
  .. .. .. .. ..$ position    :List of 4
  .. .. .. .. .. ..$ code        : chr "C"
  .. .. .. .. .. ..$ name        : chr "Center"
  .. .. .. .. .. ..$ type        : chr "Forward"
  .. .. .. .. .. .. [list output truncated]
  .. .. .. .. .. [list output truncated]
  .. .. .. ..$ ID8476967:List of 4
  .. .. .. .. ..$ person      :List of 22
  .. .. .. .. .. ..$ id                : int 8476967
  .. .. .. .. .. ..$ fullName          : chr "Brett Kulak"
  .. .. .. .. .. ..$ link              : chr "/api/v1/people/8476967"
  .. .. .. .. .. .. [list output truncated]
  .. .. .. .. ..$ jerseyNumber: chr "77"
  .. .. .. .. ..$ position    :List of 4
  .. .. .. .. .. ..$ code        : chr "D"
  .. .. .. .. .. ..$ name        : chr "Defenseman"
  .. .. .. .. .. ..$ type        : chr "Defenseman"
  .. .. .. .. .. .. [list output truncated]
  .. .. .. .. .. [list output truncated]
  .. .. .. .. [list output truncated]
  .. .. .. [list output truncated]
  ..$ officials:'data.frame':	5 obs. of  4 variables:
  .. ..$ officialType     : chr [1:5] "Referee" "Referee" "Referee" "Linesman" ...
  .. ..$ official.id      : int [1:5] 4621 2275 4692 2329 2460
  .. ..$ official.fullName: chr [1:5] "Graham Skilliter" "Marc Joannette" "Kendrick Nicholson" "Steve Barton" ...
  .. .. [list output truncated]
  ..- attr(*, "url")= chr "https://statsapi.web.nhl.com/api/v1/game/2020030174/boxscore"

As you can see even truncated to 3 level, this thing is quite big, I'm only interested in the players list, I would to create a dataframe where every item of those list below is a column and every ID would be a row.

Top answer
1 of 5
4

This is a pipe-able (%>%) base R approach

select_unnest <- function(x, select_val){
  x[[2]][x[[1]]==select_val][[1]]
}

nest_2 %>% select_unnest("Asia") %>% select_unnest("China")

Comparing the timings:

Unit: microseconds

                min        lq      mean   median        uq       max neval
aosmith1   3202.105 3354.0055 4045.9602 3612.126 4179.9610 17119.495   100
aosmith2   5797.744 6191.9380 7327.6619 6716.445 7662.6415 24245.779   100
Floo0       227.169  303.3280  414.3779  346.135  400.6735  4804.500   100
Ben Bolker  622.267  720.6015  852.9727  775.172  875.5985  1942.495   100

Code:

microbenchmark::microbenchmark(
  {a<-nest_2[nest_2$continent=="Asia",]$by_continent
  flatten_df(a) %>%
    filter(country == "China") %>%
    unnest},
  {nest_2 %>%
      filter(continent == "Asia") %>%
      select(by_continent) %>%
      unnest%>%
      filter(country == "China") %>%
      unnest},
  {nest_2 %>% select_unnest("Asia") %>% select_unnest("China")},
  {n1 <- nest_2$by_continent[nest_2$continent=="Asia"][[1]]
  n2 <- n1 %>% filter(country=="China")
  n2$by_country[[1]]}
)
2 of 5
2

Your a is still a list, which would need to be flattened before you could do more.

You could use flatten_df, dplyr::filter, and unnest:

library(dplyr)

flatten_df(a) %>%
    filter(country == "China") %>%
    unnest

# A tibble: 12 x 5
   country  year  lifeExp        pop gdpPercap
    <fctr> <int>    <dbl>      <int>     <dbl>
1    China  1952 44.00000  556263527  400.4486
2    China  1957 50.54896  637408000  575.9870
3    China  1962 44.50136  665770000  487.6740
4    China  1967 58.38112  754550000  612.7057
5    China  1972 63.11888  862030000  676.9001
6    China  1977 63.96736  943455000  741.2375
7    China  1982 65.52500 1000281000  962.4214
8    China  1987 67.27400 1084035000 1378.9040
9    China  1992 68.69000 1164970000 1655.7842
10   China  1997 70.42600 1230075000 2289.2341
11   China  2002 72.02800 1280400000 3119.2809
12   China  2007 72.96100 1318683096 4959.1149

An alternative way to pull out Asia and end up in a situation where you aren't working with a list. This would avoid the need to flatten later.

asia = nest_2 %>%
    filter(continent == "Asia") %>%
    select(by_continent) %>%
    unnest
Find elsewhere
🌐
Learn By Example
learnbyexample.org › r-list
R List - Learn By Example
April 20, 2020 - You can access individual items in a nested list by using the combination of [[]] or $ operator and the [] operator. lst <- list(item1 = 3.14, item2 = list(item2a = 5:10, item2b = c("a","b","c"))) # preserve the output as a list lst[[2]][1] ...
🌐
TutorialsPoint
tutorialspoint.com › how-to-access-elements-of-nested-lists-in-r
How to access elements of nested lists in R?
August 10, 2020 - > x1<-c(list(1:5),list(6:10),list(11:15)) > x2<-c(list(letters[1:5]),list(letters[6:10], list(letters[11:15]))) > x3<-c(list(c("India","Australia"),list("Canada"),list(c("Russia","Malaysia")))) > x4<-c(list("Europe"),list(c("Asia","America"),list(c("Africa","Antartica")))) > x5<-c(list("Red"),list("Green"),list("Yellow"),list(c("White","Pink"))) > Total_Lists<-list(x1,x2,x3,x4,x5)
🌐
R-bloggers
r-bloggers.com › r bloggers › map and nested lists
Map and Nested Lists | R-bloggers
April 27, 2022 - The . inside the mutate() and split() functions are pronouns standing for “the thing we’re referring to/computing on right now”. In this case, that’s “the current data frame as we iterate through df_list”. Now we have a nested list. Each of df_1 to df_5 is split into an over or under table. The whole thing looks like this: ... We can look at particular pieces of this by e.g. ... This is handy because we can use tab completion in our IDE to investigate the tables in the list. We could just work with the list like this.
🌐
R-bloggers
r-bloggers.com › r bloggers › uncategorized › processing nested lists
Processing nested lists | R-bloggers
April 28, 2011 - # Nested lists code, an example # Make a nested list mylist <- list() mylist_ <- list() for(i in 1:5) { for(j in 1:5) { mylist[[j]] <- i*j } mylist_[[i]] <- mylist } # return values from first part of list laply(mylist_[[1]], identity) [1] 1 2 3 4 5 # return all values laply(mylist_, function(x) laply(x, identity)) 1 2 3 4 5 [1,] 1 2 3 4 5 [2,] 2 4 6 8 10 [3,] 3 6 9 12 15 [4,] 4 8 12 16 20 [5,] 5 10 15 20 25 # perform some function, in this case sqrt of each value laply(mylist_, function(x) laply(x, function(x) sqrt(x))) 1 2 3 4 5 [1,] 1.000000 1.414214 1.732051 2.000000 2.236068 [2,] 1.414214 2.000000 2.449490 2.828427 3.162278 [3,] 1.732051 2.449490 3.000000 3.464102 3.872983 [4,] 2.000000 2.828427 3.464102 4.000000 4.472136 [5,] 2.236068 3.162278 3.872983 4.472136 5.000000
🌐
GeeksforGeeks
geeksforgeeks.org › r language › convert-nested-lists-to-dataframe-in-r
Convert Nested Lists to Dataframe in R - GeeksforGeeks
November 15, 2021 - Create dataframe using data.frame function with the do.call and rbind. rbind is used to bind the lists together by row into data frame. do.call is used to bind the rbind and the nested list together as a single argument in the Data frame function.
🌐
YouTube
youtube.com › joshua french
Nested lists in R - YouTube
We discuss creation and subsetting a nested list in R.Materials are available at https://github.com/jfrench/DataWrangleViz/blob/master/07-matrices-arrays-lis...
Published   October 17, 2023
Views   127
🌐
Rdrr.io
rdrr.io › cran › rlist › man › list.flatten.html
list.flatten: Flatten a nested list to a one-level list in rlist: A Toolbox for Non-Tabular Data Manipulation
September 5, 2021 - list.parse: Convert an object to list with identical structure · list.prepend: Prepend elements to a list · list.rbind: Bind all list elements by row · list.remove: Remove members from a list by index or name · list.reverse: Reverse a list · list.sample: Sample a list or vector · list.save: Save a list to a file · list.search: Search a list recusively by an expression · Browse all... Home · / CRAN · / rlist · / list.flatten: Flatten a nested list to a one-level list ·
🌐
Stack Overflow
stackoverflow.com › questions › 77644384 › how-to-efficiently-manipulate-the-contents-of-nested-lists-in-r
How to efficiently manipulate the contents of nested lists in R - Stack Overflow
For multiple reasons Reproducible ... want to do, but an efficient way to work with deeply nested lists is to use vectors as indices into the top level....
🌐
Stack Overflow
stackoverflow.com › questions › 67138581 › r-apply-function-to-nested-lists
R: Apply function to nested lists - Stack Overflow
Does it mean that "relist" just takes the structure from nested_lons1? 2021-04-18T15:00:42.887Z+00:00 ... Yes. All of the lists must have the same structure so any one of them would work. The function is just copying the structure of the list, not the data. 2021-04-18T16:16:01.303Z+00:00 ... Find the answer to your question by asking. Ask question ... See similar questions with these tags.
🌐
Reddit
reddit.com › r/rstudio › is there a way to directly update a nested list from within a function in r?
r/RStudio on Reddit: Is there a way to directly update a nested list from within a function in R?
November 11, 2021 -

I've been banging my head against a wall on this and assign() doesn't appear to be the answer. If anyone has any suggestions, I have to save from within the function so that my user input doesn't become the next line of code because I am using readline().

Edit: I think others unfamiliar with functions may not understand the issue: list[[x]] <- update.object. That doesn't work. It is inside a function. It will not write any object to the global environment unless you tell it to. Assign() allows for this but not for nested lists. So I am not sure how to do so.

Edit: reproducible example available here: https://stackoverflow.com/questions/69934750/updating-a-nested-list-object-in-the-global-environment-from-within-a-function-i