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

Time:12-13

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

CodePudding user response:

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)}
  • Related