Back

Explore Courses Blog Tutorials Interview Questions
+1 vote
4 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 (46k 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.

Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers

500 comments

94.2k users

Browse Categories

...