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

cannot use pipeline in `intersect()` in R with dplyr package

Context

I want to use intersect() with two character vectors, and I can do this straightway using intersect(names(mtcars), a). But when I used pipeline an error occured.

Question

How can I use pipeline in intersect() in R with dplyr package.

Reproducible code

library(tidyverse)

a = c('mpg', 'cyl')

intersect(names(mtcars), a) # run correctly

mtcars %>% intersect(x = names(.), y = a) # error occur

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 :

From the magrittr readme:

Re-using the placeholder for attributes

It is straightforward to use the placeholder several times in a right-hand side expression. However, when the placeholder only appears in a nested expressions magrittr will still apply the first-argument rule. The reason is that in most cases this results more clean code.

x %>% f(y = nrow(.), z = ncol(.)) is equivalent to f(x, y = nrow(x), z = ncol(x))

The behavior can be overruled by enclosing the right-hand side in braces:

x %>% {f(y = nrow(.), z = ncol(.))} is equivalent to f(y = nrow(x), z = ncol(x))

So you have two options:

# straightforward
mtcars %>% names() %>% intersect(a)

# using the documented "overrule"
mtcars %>% {intersect(x = names(.), y = a)}
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