Use of -> assignment operator in R




I was learning about the different ways of assigning values to variables in R. I know that the standard assignment operator is ‘<-’. however there are other operators like ‘=’, ‘->’ and even the assign() function.

What are the different situations where we may need to use operators other than the standard assignment operator, especially the ‘->’ operator?

Thank you.


The ‘<-’ and ‘=’ operator mean the same.In earlier versions of R there were some differences,but in the new versions they are the same.
For the -> operator:

> x <- 5
> x
[1] 5
> y <- 10
> x + y -> z
> z
[1] 15

Hope this helps!!


Read this . btw I use = and not <- because it takes me one finger to type = and three finger strokes to type <- and the engineer in me just wants to be efficient .

when the R language (and S before it) was first created, <- was the only choice of assignment operator. This is a hangover from the language APL, where the arrow notation was used to distinguish assignment (assign the value 3 to x) from equality (is x equal to 3?). (Professor Ripley reminds me that on APL keyboards there was an actual key on the keyboard with the arrow symbol on it, so the arrow was a single keystroke back then. The same was true of the AT&T terminals first used for the predecessors of S as described in the Blue Book.) However many modern languages (such as C, for example) use = for assignment, so beginners using R often found the arrow notation cumbersome, and were prone to use = by mistake. But R uses = for yet another purpose: associating function arguments with values (as in pnorm(1, sd=2), to set the standard deviation to 2).
To make things easier for new users familiar with languages like C, R added the capability in 2001 to also allow = be used as an assignment operator, on the basis that the intent (assignment or association) is usually clear by context. So,
x = 3

clearly means “assign 3 to x”, whereas

f(x = 3)

clearly means “call function f, setting the argument x to 3”.

There is one case where ambiguity might occur: if you wanted to assign a variable during a function call. The only way to do this in modern versions of R is:
f(x <- 3)


but also read this

##Delete x (if it exists)

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 <- operator:

mean(x <- 1:10)# [1] 5.5
x # [1] 1 2 3 4 5 6 7 8 9 10

This time the x variable is declared within the user workspace.