What are the differences between the assignment operators = and <- in R?

I know that operators are slightly different, as this example shows

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

But is this the only difference?

  • 45
    As noted here the origins of the <- symbol come from old APL keyboards that actually had a single <- key on them. – joran Dec 12 '14 at 17:35


As your example shows, = and <- have slightly different operator precedence (which determines the order of evaluation when they are mixed in the same expression). In fact, ?Syntax in R gives the following operator precedence table, from highest to lowest:

‘-> ->>’           rightwards assignment
‘<- <<-’           assignment (right to left)
‘=’                assignment (right to left)

But is this the only difference?

Since you were asking about the assignment operators: yes, that is the only difference. However, you would be forgiven for believing otherwise. Even the R documentation of ?assignOps claims that there are more differences:


Let’s not put too fine a point on it: the R documentation is (subtly) wrong [1]. This is easy to show: we just need to find a counter-example of the = operator that isn’t (a) at the top level, nor (b) a subexpression in a braced list of expressions (i.e. {…; …}). — Without further ado:

# Error: object 'x' not found
sum((x = 1), 2)
# [1] 3
# [1] 1

Clearly we’ve performed an assignment, using =, outside of contexts (a) and (b). So, why has the documentation of a core R language feature been wrong for decades?

It’s because in R’s syntax the symbol = has two distinct meanings that get routinely conflated:

  1. The first meaning is as an assignment operator. This is all we’ve talked about so far.
  2. The second meaning isn’t an operator but rather a syntax token that signals named argument passing in a function call. Unlike the = operator it performs no action at runtime, it merely changes the way an expression is parsed.

Let’s see.

In any piece of code of the general form …

‹function_name›(‹argname› = ‹value›, …)
‹function_name›(‹args›, ‹argname› = ‹value›, …)

… the = is the token that defines named argument passing: it is not the assignment operator. Furthermore, = is entirely forbidden in some syntactic contexts:

if (‹var› = ‹value›) …
while (‹var› = ‹value›) …
for (‹var› = ‹value› in ‹value2›) …
for (‹var1› in ‹var2› = ‹value›) …

Any of these will raise an error “unexpected '=' in ‹bla›”.

In any other context, = refers to the assignment operator call. In particular, merely putting parentheses around the subexpression makes any of the above (a) valid, and (b) an assignment. For instance, the following performs assignment:

median((x = 1 : 10))

But also:

if (! (nf = length(from))) return()

Now you might object that such code is atrocious (and you may be right). But I took this code from the base::file.copy function (replacing <- with =) — it’s a pervasive pattern in much of the core R codebase.

The original explanation by John Chambers, which the the R documentation is probably based on, actually explains this correctly:

[= assignment is] allowed in only two places in the grammar: at the top level (as a complete program or user-typed expression); and when isolated from surrounding logical structure, by braces or an extra pair of parentheses.

A confession: I lied earlier. There is one additional difference between the = and <- operators: they call distinct functions. By default these functions do the same thing but you can override either of them separately to change the behaviour. By contrast, <- and -> (left-to-right assignment), though syntactically distinct, always call the same function. Overriding one also overrides the other. Knowing this is rarely practical but it can be used for some fun shenanigans.

| improve this answer | |
  • 1
    About the precedence, and errors in R's doc, the precedence of ? is actually right in between = and <-, which has important consequences when overriding ? , and virtually none otherwise. – Moody_Mudskipper Jan 10 at 0:12
  • @Moody_Mudskipper that’s bizarre! You seem to be right, but according to the source code (main/gram.y), the precedence of ? is correctly documented, and is lower than both = and <-. – Konrad Rudolph Jan 10 at 10:13
  • I don't speak C but I suppose that = get a special treatment before the parse tree is built. Maybe related to function arguments, it makes sense that in foo(x = a ? b) we'd look for = before parsing rest of the expression. – Moody_Mudskipper Jan 10 at 10:34
  • @Moody_Mudskipper I’ve asked r-devel – Konrad Rudolph Jan 10 at 11:16
  • 2
    @Moody_Mudskipper FWIW this is finally fixed in 4.0.0. – Konrad Rudolph Apr 24 at 13:17

The difference in assignment operators is clearer when you use them to set an argument value in a function call. For example:

median(x = 1:10)
## Error: object 'x' not found

In this case, x is declared within the scope of the function, so it does not exist in the user workspace.

median(x <- 1:10)

In this case, x is declared in the user workspace, so you can use it after the function call has been completed.

There is a general preference among the R community for using <- for assignment (other than in function signatures) for compatibility with (very) old versions of S-Plus. Note that the spaces help to clarify situations like

# Does this mean assignment?
x <- 3
# Or less than?
x < -3

Most R IDEs have keyboard shortcuts to make <- easier to type. Ctrl + = in Architect, Alt + - in RStudio (Option + - under macOS), Shift + - (underscore) in emacs+ESS.

If you prefer writing = to <- but want to use the more common assignment symbol for publicly released code (on CRAN, for example), then you can use one of the tidy_* functions in the formatR package to automatically replace = with <-.

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

The answer to the question "Why does x <- y = 5 throw an error but not x <- y <- 5?" is "It's down to the magic contained in the parser". R's syntax contains many ambiguous cases that have to be resolved one way or another. The parser chooses to resolve the bits of the expression in different orders depending on whether = or <- was used.

To understand what is happening, you need to know that assignment silently returns the value that was assigned. You can see that more clearly by explicitly printing, for example print(x <- 2 + 3).

Secondly, it's clearer if we use prefix notation for assignment. So

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

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

The parser interprets x <- y <- 5 as

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

We might expect that x <- y = 5 would then be

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

but actually it gets interpreted as

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

This is because = is lower precedence than <-, as shown on the ?Syntax help page.

| improve this answer | |
  • 4
    This is also mentioned in chapter 8.2.26 of The R Inferno by Patrick Burns (Not me but a recommendation anyway) – Uwe Jun 14 '16 at 9:17
  • 3
    However, median((x = 1:10)) has the same effect as median(x <- 1:10). – Francesco Napolitano Sep 27 '16 at 13:27
  • 2
    i dont really consider them shortcuts, in any case you press same number of keys – yosemite_k Jun 8 '18 at 12:42
  • 5
    I just realised that your explanation of how x <- x = 5 gets interpreted is slightly wrong: In reality, R interprets it as ​`<-<-`(x, y = 5, value = 5) (which itself is more or less equivalent to tmp <- x; x <- `<-<-`(tmp, y = 5, value = 5)). Yikes! – Konrad Rudolph Jul 27 '18 at 11:25
  • 4
    … And I just realised that the very first part of this answer is incorrect and, unfortunately, quite misleading because it perpetuates a common misconception: The way you use = in a function call does not perform assignment, and isn’t an assignment operator. It’s an entirely distinct parsed R expression, which just happens to use the same character. Further, the code you show does not “declare” x in the scope of the function. The function declaration performs said declaration. The function call doesn’t (it gets a bit more complicated with named ... arguments). – Konrad Rudolph Apr 12 '19 at 10:33

Google's R style guide simplifies the issue by prohibiting the "=" for assignment. Not a bad choice.


The R manual goes into nice detail on all 5 assignment operators.


| improve this answer | |
  • 133
    The downside of accidental assignment by x<-y when x < -y was meant, vexes me so much that I personally prefer =. Having your code depend on whitespace being present doesn't seem good to me. It's ok to suggest spacing as style advice but for your code to run differently whether a space is there or not? What if you reformat your code, or use search and replace, the whitespace can sometimes disappear and code goes awry. That isn't a problem with =. IIUC, prohibiting = equates to requiring "<- "; i.e., 3 characters including a space, not just "<-". – Matt Dowle Jun 8 '12 at 15:16
  • 12
    Note that any non-0 is considered TRUE by R. So if you intend to test if x is less than -y, you might write if (x<-y) which will not warn or error, and appear to work fine. It'll only be FALSE when y=0, though. – Matt Dowle Jun 8 '12 at 15:21
  • 4
    If you do prohibit = and use <- then it's hard to argue that an extra step of grep "[^<]<-[^ ]" *.R isn't needed. = doesn't need such a grep. – Matt Dowle Jun 8 '12 at 15:28
  • 34
    Why hurt your eyes and finger with <- if you can use =? In 99.99% of times = is fine. Sometimes you need <<- though, which is a different history. – Fernando Oct 9 '13 at 1:22
  • 10
    The focus on <- is perhaps one of the lame reasons for the lack of += and -=. – Chris Nov 11 '15 at 5:07

x = y = 5 is equivalent to x = (y = 5), because the assignment operators "group" right to left, which works. Meaning: assign 5 to y, leaving the number 5; and then assign that 5 to x.

This is not the same as (x = y) = 5, which doesn't work! Meaning: assign the value of y to x, leaving the value of y; and then assign 5 to, umm..., what exactly?

When you mix the different kinds of assignment operators, <- binds tighter than =. So x = y <- 5 is interpreted as x = (y <- 5), which is the case that makes sense.

Unfortunately, x <- y = 5 is interpreted as (x <- y) = 5, which is the case that doesn't work!

See ?Syntax and ?assignOps for the precedence (binding) and grouping rules.

| improve this answer | |
  • Yes, as Konrad Rudolph's answer said <- <<- is above of = in precedence table, which means <- will be exectued first. So, x <- y = 5 should be executed as (x <- y) = 5. – Nick Dong Apr 19 '19 at 3:04
  • 1
    @Nick Dong Yes indeed. Helpfully, the operator precedendence table is documented unambiguously in ?Syntax {base}. – Steve Pitchers Apr 28 '19 at 17:38

According to John Chambers, the operator = is only allowed at "the top level," which means it is not allowed in control structures like if, making the following programming error illegal.

> if(x = 0) 1 else x
Error: syntax error

As he writes, "Disallowing the new assignment form [=] in control expressions avoids programming errors (such as the example above) that are more likely with the equal operator than with other S assignments."

You can manage to do this if it's "isolated from surrounding logical structure, by braces or an extra pair of parentheses," so if ((x = 0)) 1 else x would work.

See http://developer.r-project.org/equalAssign.html

| improve this answer | |
  • 11
    It's a common bug, x==0 is almost always meant instead. – Aaron left Stack Overflow Sep 15 '14 at 15:04
  • 14
    Ah, yes, I overlooked that you said "programming error". It's actually good news that this causes an error. And a good reason to prefer x=0 as assignment over x<-0! – Steve Pitchers Sep 16 '14 at 9:55
  • 7
    Yes, it is nice that this causes an error, though I draw a different lesson about what to prefer; I choose to use = as little as possible because = and == look so similar. – Aaron left Stack Overflow Sep 16 '14 at 16:09
  • 2
    The way this example is presented is so strange to me. if(x = 0) 1 else x throws an error, helping me find and correct a bug. if(x <- 1) 1 else x doesn't throw an error and is very confusing. – Gregor Thomas Feb 24 '17 at 21:32
  • 3
    I mean, a really helpful error checker would throw an error there and say "you have useless code that will always return the else value, did you mean to write it that way?", but, that may be a pipe dream... – TylerH Mar 8 '17 at 17:13


| improve this answer | |
  • 8
    I think "top level" means at the statement level, rather than the expression level. So x <- 42 on its own is a statement; in if (x <- 42) {} it would be an expression, and isn't valid. To be clear, this has nothing to do with whether you are in the global environment or not. – Steve Pitchers Sep 16 '14 at 9:58
  • 1
    This: “the operator = is only allowed at the top level” is a widely held misunderstanding and completely wrong. – Konrad Rudolph Mar 2 '17 at 14:20
  • This is not true - for example, this works, even though assignment is not a complete expression: 1 + (x = 2) – Pavel Minaev Mar 5 '17 at 22:52
  • 1
    To clarify the comments by KonradRudolph and PavelMinaev, I think it's too strong to say that it's completely wrong, but there is an exception, which is when it's "isolated from surrounding logical structure, by braces or an extra pair of parentheses." – Aaron left Stack Overflow Oct 15 '19 at 13:57
  • Or in function() x = 1, repeat x = 1, if (TRUE) x = 1.... – Moody_Mudskipper Jan 10 at 0:18

This may also add to understanding of the difference between those two operators:

df <- data.frame(
      a = rnorm(10),
      b <- rnorm(10)

For the first element R has assigned values and proper name, while the name of the second element looks a bit strange.

# 'data.frame': 10 obs. of  2 variables:
#  $ a             : num  0.6393 1.125 -1.2514 0.0729 -1.3292 ...
#  $ b....rnorm.10.: num  0.2485 0.0391 -1.6532 -0.3366 1.1951 ...

R version 3.3.2 (2016-10-31); macOS Sierra 10.12.1

| improve this answer | |
  • 6
    can you give a more detailed explaination of why this happens/what's going on here? (hint: data.frame tries to use the name of the provided variable as the name of the element in the data frame) – Ben Bolker Dec 10 '16 at 22:16
  • Just thought, could this possibly be a bug? And if so, how and where do I report it? – Denis Rasulev Jul 15 '17 at 6:27
  • 7
    it's not a bug. I tried to hint at the answer in my comment above. When setting the name of the element, R will use the equivalent of make.names("b <- rnorm(10)"). – Ben Bolker Jul 16 '17 at 15:21
