Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to continue tidyr/dplyr/tidyverse %>% commands to the next line?

I have a long command with a long line of dplyr/tidyr commands:

Object %>% mutate() %>% select() %>% separate() %>% separate() %>% separate %>% separate() %>% separate() %>% select()

and I want to separate it into multiple lines for readability sake, is there a way to do this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
x = 1 +
2

The first 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.

By contrast, the second 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading