Why put + and %>% at the end of lines?

Because R doesn't require an explicit statement terminator (like the semi-colon in C/C++/many other languages), the R interpreter/compiler will determine that a statement is complete whenever there is a line that completes the statement. So, the following is a valid R statement:

delays <- flights

During execution, after reaching the end of that line, R will stop and execute that complete statement. It then reaches the next line

    %>% group_by(dest)

That is not a valid statement (and can't be turned into such by additional code), since %>% is a binary operator (along with +) and requires code on both sides of it.

Changing that so that allowing leading binary operators to continue statements would require changing R to look ahead to subsequent lines to see if the statement is being continued. While that would allow your preferred style, I'm sure it would have some problems. Even knowing little-to-nothing about the interpreter inner workings, the following would be highly ambiguous:

x <- 1
-1

Both lines are valid statements, but the negation operator - could also be subtraction if you looked ahead.

Edit: If it's a problem on a regular basis while you develop code, you could end your %>% chains with {.}:

delays <- flights %>%
    group_by(dest) %>%
    #summarise(distance = mean(distance)) %>%
    {.}

That last statement is basically an identity operator for pipes and will not change the output. I'm not sure what the ggplot2 equivalent would be offhand.

8 Likes