R - Assign value to list of lists in a for loop

Viewed 524

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 Answers

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
Related