Reputation: 9
All I can find is how to write to global variables, but not how to read them.
Example of incorrect code:
v = 0;
test <- function(v) {
v ->> global_v;
v <<- global_v + v;
}
test(1);
print(v);
This yields 2
because v ->> global_v
treats v
as the local variable v
which is equal to 1. What can I replace that line with for global_v
to get the 0 from the global v
?
I'm asking of course about solutions different to "use different variable names".
Upvotes: 0
Views: 67
Reputation: 1237
You can use with(globalenv(), v)
to evaluate v
in the global environment rather than the function. with
constructs an environment from its first argument, and evaluates the subsequent arguments in that environment. globalenv()
returns the global environment. Putting those together, your function would become this:
test <- function(v) {
v <<- with(globalenv(), v) + v;
}
Upvotes: 1