+1 vote
2 views
in R Programming by (3.4k points)
edited by

Can someone state the difference between the assignment operators = and <- in R?

Is this the only difference in both these operators mentioned in the example below:

x <- y <- 6

x = y = 6

x = y <- 6

x <- y = 6

# Error in (x <- y) = 6 : could not find function "<-<-"

1 Answer

0 votes
by (46.1k points)
edited by

The operator <- can be used anywhere whereas the operator = can only be used at top level. It will be more clearer when it’s used to set an argument value in function call.

You can also use one of the tidy_* functions in the formatR  and it will automatically replace = with <-. Ex.

library(formatR)

   tidy_source(text = "x=1:5", arrow = TRUE)

   ## x <- 1:5

To fix the error of your syntax use prefix notation for assignment.

x <- 6

`<-`(x, 6) #same thing

y = 6 `=`(y, 6)  #also the same thing

parser interprets x <- y <- 6 as

`<-`(x, `<-`(y, 6))

Our expectation is that x <- y = 6 would then be

`<-`(x, `=`(y, 6))

but actually it will result as

`=`(`<-`(x, y), 6)

This is happening because = is lower precedence than <-

Hope this helps.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Jul 19, 2019 in R Programming by Ajinkya757 (5.3k points)
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...