R generally continues reading more lines until it has read a complete expression. You can therefore break an expression across multiple lines by ensuring that, at the end of a given line, there’s no complete expression.
Consider
x = 1
+ 2
This code has a complete expression on its first line (x = 1
is a valid, complete expression) so R does not continue to the next line — it evaluates the expression x = 1
. Afterwards, x
has the value 1.
x = 1 +
2
By contrast, this piece of code does not have a complete expression on its first line (x = 1 +
would be invalid) so R continues to the next line and only then evaluates the expression x = 1 + 2
. Afterwards, x
has the value 3.
The same is true for the %>%
operator. So you have multiple choices. For instance, and this is the generally recommended way, you can end lines in %>%
:
Object %>%
mutate() %>%
select() %>%
…
Conversely, some people prefer having %>%
at the beginning of a line. But to make this work we need to do something to make the expression not-complete. Easy: wrap it in parentheses:
(Object
%>% mutate()
%>% select()
%>% …
)
This second style is decidedly less common (and some people actively dislike it because of the redundant parentheses, which add visual clutter), but it does have its proponents.