Reputation: 462
I am trying to run some code inside local() in R so I don't have a bunch of nuisance variables in my environment, but I just realized that I can't define a new variable within local(). For example:
local(
var1 = 1
print(var1)
)
gives me the following error:
Error: unexpected symbol in:
" var1 = 1
print"
> )
Error: unexpected ')' in ")"
>
But if I create a variable in a forloop within local() then it's OK; the following code runs:
local(
for (v in 1:3) {
var1 = v
print(var1)
}
)
Why is this?
Update: the following code works (if I include everything in local() in curly brackets
local(
{var1 = 1
print(var1)}
)
Again, what is the difference here?
Upvotes: 1
Views: 177
Reputation: 2431
Check out the documentation in: ?`{`. Look especially at examples:
(2+3)
(2+3
4+5)
{2+3}
{2+3
4+5}
Upvotes: 1
Reputation: 15072
local
has one main argument, expr
. Your first code is written that it would be interpreted as two arguments. For example, see the below example, where your first code's logic would expect to work regardless of where var1
is defined. Wrapping in curly braces creates an expression object that becomes a single argument to local. The for
loop does much the same thing.
local(
var1 = 1
print(1)
)
#> Error: <text>:4:3: unexpected symbol
#> 3: var1 = 1
#> 4: print
#> ^
Created on 2018-05-01 by the reprex package (v0.2.0).
Upvotes: 1