From 8f3c562441cfe81b3208fa48664fd55093a6fcc4 Mon Sep 17 00:00:00 2001 From: micabo <37561518+micabo@users.noreply.github.com> Date: Wed, 3 Jan 2024 11:27:45 +0100 Subject: [PATCH] Update Expressions.Rmd - Correct the ggplot2 example to shows the non-associativity of `+` (i.e. include a new example). - Keep the original example as an additional point to show the non-commutative nature of `+`. --- Expressions.Rmd | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Expressions.Rmd b/Expressions.Rmd index 38f03011b..cbf5f1357 100644 --- a/Expressions.Rmd +++ b/Expressions.Rmd @@ -473,7 +473,8 @@ Note the appearance of the parentheses in the AST as a call to the `(` function. ### Associativity -The second source of ambiguity is introduced by repeated usage of the same infix function. For example, is `1 + 2 + 3` equivalent to `(1 + 2) + 3` or to `1 + (2 + 3)`? This normally doesn't matter because `x + (y + z) == (x + y) + z`, i.e. addition is associative, but is needed because some S3 classes define `+` in a non-associative way. For example, ggplot2 overloads `+` to build up a complex plot from simple pieces; this is non-associative because earlier layers are drawn underneath later layers (i.e. `geom_point()` + `geom_smooth()` does not yield the same plot as `geom_smooth()` + `geom_point()`). +The second source of ambiguity is introduced by repeated usage of the same infix function. For example, is `1 + 2 + 3` equivalent to `(1 + 2) + 3` or to `1 + (2 + 3)`? This normally doesn't matter because `x + (y + z) == (x + y) + z`, i.e. addition is associative, but is needed because some S3 classes define `+` in a non-associative way. For example, ggplot2 overloads `+` to build up a complex plot from simple pieces. This is non-associative because the plot must be initialized before a layer is added to it: `(ggplot(mtcars, aes(x = disp, y = mpg)) + geom_point()) + geom_smooth()` will work, while `ggplot(mtcars, aes(x = disp, y = mpg)) + (geom_point() + geom_smooth())` will not. +Furthermore, this is also non-commutative because later layers are drawn on top of earlier layers (i.e. `geom_point()` + `geom_smooth()` does not yield the same plot as `geom_smooth()` + `geom_point()`). In R, most operators are __left-associative__, i.e. the operations on the left are evaluated first: