What’s the difference?
The main difference between the two assignment operators is scope. It’s easiest to see the difference with an example:
##Delete x (if it exists)
> rm(x)
> mean(x=1:10) #[1] 5.5
> x #Error: object 'x' not found
Here x is declared within the function’s scope of the function, so it doesn’t exist in the user workspace. Now, let’s run the same piece of code with using the
> mean(x
> x # [1] 1 2 3 4 5 6 7 8 9 10
This time the x variable is declared within the user workspace.
When does the assignment take place?
In the code above, you may be tempted to thing that we “assign 1:10 to x, then calculate the mean.” This would be true for languages such as C, but it isn’t true in R. Consider the following function:
> a
> f
> f
[1] TRUE
[1] 1
Notice that the value of a hasn’t changed! In R, the value of a will only change if we need to evaluate the argument in the function. This can lead to unpredictable behaviour:
> f 0.5) TRUE else a
> f(a
[1] 2
> f(a
[1] TRUE
[1] 2
> f(a
[1] 3