The superassignment operator and other scope-breaking techniques should be avoided if at all possible, in particular because it makes for unclear code and confusing situations like these. But if you really, truly had to assign values to a variable that is out of scope, you could use standard assignment inside eval
:
a <- c(1,2,3)
eval(a[3] <- 4, envir = -1)
a
[1] 1 2 4
To generalize this further (if performing the assignment inside a function), you may need to use <<-
inside eval
anyway.
While changing variables out of scope is still a bad idea, using eval
at least makes the operation more explicit, since you have to specify the environment in which the expression is to be evaluated.
All that said, scope-breaking assignments are never necessary, per se, and you should perhaps find a way to write your script such that this is not relied on.