Assignment to replace value in nonlocal list Assignment to replace value in nonlocal list r r

Assignment to replace value in nonlocal list


The R-language definition (section 2.1.10) says:

Unlike most other R objects, environments are not copied when passed to functions or used in assignments.

Section "6.3 More on evaluation" also gives a slightly relevant hint:

Notice that evaluation in a given environment may actually change that environment, most obviously in cases involving the assignment operator, such as

eval(quote(total <- 0), environment(robert$balance)) # rob Rob

This is also true when evaluating in lists, but the original list does not change because one is really working on a copy.

So, the answer to your first question is that lists need to be copied to assign into them, but environments can be modified in place (which has huge performance implications).

Regarding your second question:

If you are working with a list, the only option seems to be to

  • copy the list into the local scope (using get),
  • assign into the list,
  • use assign to copy the modified list back into the original environment.