I have 2 questions here. When using a for loop to iterate through a list of lists in R:
- What is R doing under the hood to copy the inner list for the for loop?
- 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})