When I have large complicated chunks of code I'll often use more parenthesis sets than are required. My code could look like this:
library(tidyverse)
mtcars %>%
mutate(name = rownames(.)) %>%
filter((cyl == 4 & grepl("Toyota", name)) |
((cyl == 6 | cyl == 8), grepl("Mazda", name)))
instead of this:
mtcars %>%
mutate(name = rownames(.)) %>%
filter(cyl == 4 & grepl("Toyota", name) |
(cyl == 6 | cyl == 8, grepl("Mazda", name)))
What can I say? In my head the parenthesis protection helps me see De Morgan's laws easier, PEMDAS easier, computational order, etc.
This liberal use of parenthesis presents a problem. Even though I would think extra parenthesis should be neutral in R and the tidyverse, they appear not to be. Look at the error I get in the code chunk below.
mtcars %>% filter((cyl == 4 & am == 1)) %>% .[1, 3]
# [1] 108
mtcars %>% filter((cyl == 4, am == 1)) %>% .[1, 3]
# Error: unexpected ',' in "mtcars %>% filter((cyl == 4,"
Why does the first example directly above work, and the second throws an error? I know the direct answer is "you're using too many parenthesis" but why can't I? It just makes life easier, for me, in these logical operator nest nightmares. I am aware of the case_when() function which does help in these type of circumstances. I still want to know why I can't use extra parenthesis though. Thank you.