2

I have 2 questions here. When using a for loop to iterate through a list of lists in R:

  1. What is R doing under the hood to copy the inner list for the for loop?
  2. How can I assign to the list to use outside of the for loop?

Here is a toy example of my lists of lists with a for loop:

list.outer = list(
    list.inner1 = list(a=0),
    list.inner2 = list(a=0)
)

for(l in list.outer){
    l$a = 5
    cat(l$a)
}
cat(list.outer$list.inner1$a,list.outer$list.inner2$a)

The output will be:

5500

I would like it to be:

5555

From my previous internet searches I figured the assign function would work, but trivial solutions like assign(l$a,5) do not.

EDIT: I am revisiting this to share a new solution for anyone that comes across this.

A function with similar behavior is lapply. This takes as input a list and a function to apply to each object in the list (in this case, each inner.list). It will hand each object to the function as the first argument and then return the objects returned by lapply (in this case each modified inner.list) stored in a new list:

list.outer = lapply(list.outer,function(innerlist){innerlist$a=5})

1 Answers1

1

Probably assign would give you the output but it is usually better to avoid it. Read Why is using assign bad?. Insted loop over the index of the list and update list itself. Try :

for(l in seq_along(list.outer)) {
   list.outer[[l]]$a  = 5
   cat(list.outer[[l]]$a)
}

#55
cat(list.outer$list.inner1$a,list.outer$list.inner2$a)
#5 5
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • I see what you are saying about going over the index. You are right and that is a working solution, but I really want to preserve the readability of the `for(list in bigger.list)` format, which is why am curious about what R is doing to make the for loop variable in that situation and if it is possible to get the behavior I want from it. – lazer-guided-lazerbeam Mar 19 '20 at 11:29
  • There maybe a way to what you are suggesting but I would not prefer doing it for the same reason mentioned above. It is not a good practice. Another option is to loop over names. `for(l in names(list.outer))` – Ronak Shah Mar 19 '20 at 11:39