Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through and modify list elements

Tags:

r

I am trying to modify a named element in a list of lists like so:

A <- list(list(a=1,b=1),list(a=2,b=2))
A[[1]]$a == 1

Try to modify the elements:

for(e in A) e$a <- 10

Why does this still hold true?

A[[1]]$a == 1

And not this:

A[[1]]$a == 10

Also, what would be the suggested approach to actually assign 10 to each .$a element?

like image 671
mgcdanny Avatar asked Jun 15 '26 23:06

mgcdanny


1 Answers

Variables in R are always values, not references (though rarely, some packages may call other languages which produce referenced objects).

The temporary iterator value created by for is not a reference to the original values being iterated. Instead, it is an independent copy. So the code below:

for (e in A) {
    e$a <- 10
}

Will not work, because the temporary variable e is a new, independent copy of an element of A, not a reference to the corresponding element in A. Since e only exists within the scope of the for loop, this code has no effect on the larger script.

A quick way to accomplish what you want would be:

for (i in 1:length(A)) {
    A[[i]]$a <- 10
}
like image 161
jdobres Avatar answered Jun 17 '26 12:06

jdobres