What's the difference between <- and = in R? Both seem to be working. Please help my dear friends.


The operators <- and = assign into the environment in which they are evaluated. The operator <- can be used anywhere, whereas the operator = is only allowed at the top level (e.g., in the complete expression typed at the command prompt) or as one of the subexpressions in a braced list of expressions.


but both of them are working like in the above example. Could you please provide an example so that I can understand clearly.

This example illustrates the previous paragraph

median(x = 1:10)
#> [1] 5.5
#> Error in eval(expr, envir, enclos): objeto 'x' no encontrado
median(x <- 1:10)
#> [1] 5.5
#>  [1]  1  2  3  4  5  6  7  8  9 10

Created on 2019-03-27 by the reprex package (v0.2.1)
When working at the top level (like in your example) there is no difference, although is customary on the R community to use <-

I ain't got any errorpct

I'm using the latest version of Rstudio by the way

That is because you already have x defined in your environment from your previous code, if you run my example on a fresh R session you would get the same result.

1 Like

Okay lemme try andresrcs

yes you are right thanks bud

Notice also:

median(x = 1:10) ## no side effect
#> [1] 5.5
median(x = y <- 1:10) ## create y in global env as side effect
#> [1] 5.5
median(y <- 1:10) ## same as above
#> [1] 5.5
median(y = 1:10) ## won't work as y is not an argument of median()
#> Error in is.factor(x): argument "x" is missing, with no default

So the best practice IMO is to stick <- to do assignments and to = to define arguments.

1 Like

For assignments <- and = are the same (there may well be exceptions I cannot recall off the top of my head), so it's a matter of taste. I think a majority of users (but not an overwhelming one) prefer <-, but some hate it.

Even more controversially you can use -> to asign the other way around, which you cannot do with =.

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.