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?
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With