18.12 Associativity

  • The second source of ambiguity is introduced by repeated usage of the same infix function.
1 + 2 + 3
#> [1] 6

# What does R do first?
(1 + 2) + 3
#> [1] 6

# or
1 + (2 + 3)
#> [1] 6
  • In this case it doesn’t matter. Other places it might, like in ggplot2.

  • In R, most operators are left-associative, i.e. the operations on the left are evaluated first:

lobstr::ast(1 + 2 + 3)
#> █─`+` 
#> ├─█─`+` 
#> │ ├─1 
#> │ └─2 
#> └─3
  • There’s two exceptions to this rule:
    1. exponentiation
    2. assignment
lobstr::ast(2 ^ 2 ^ 3)
# █─`^`
# ├─2
# └─█─`^`
#   ├─2
#   └─3
lobstr::ast(x <- y <- z)
#> █─`<-` 
#> ├─x 
#> └─█─`<-` 
#>   ├─y 
#>   └─z
# █─`<-`
# ├─x
# └─█─`<-`
#   ├─y
#   └─z