Taran
Taran

Reputation: 365

Using the dot operator in dplyr::bind_cols

I'm seeing some unexpected behavior with dplyr. I have a specific use case but I will setup a dummy problem to illustrate my point. Why does this work,

library(dplyr)
temp <- bind_cols(mtcars %>% select(-mpg), mtcars %>% select(mpg))
head(temp)

cyl  disp  hp drat    wt  qsec vs am gear carb  mpg
6 160.0 110 3.90 2.620 16.46  0  1    4    4 21.0
6 160.0 110 3.90 2.875 17.02  0  1    4    4 21.0

But not this,

library(dplyr)
temp <- mtcars %>% bind_cols(. %>% select(-mpg), . %>% select(mpg))

Error in cbind_all(x) : Argument 2 must be length 1, not 32

Thanks for the help.

Upvotes: 5

Views: 1000

Answers (2)

Marco Sandri
Marco Sandri

Reputation: 24252

Another solution:

myfun <- function(x) {
  bind_cols(x %>% select(-mpg), x %>% select(mpg))
}
temp <- mtcars %>% myfun

Upvotes: 0

acylam
acylam

Reputation: 18681

You need to wrap your function with {} to pipe mtcars into a function within another function like the following:

library(dplyr)

temp1 = mtcars %>% {bind_cols(select(., -mpg), select(., mpg))}
temp2 = bind_cols(mtcars %>% select(-mpg), mtcars %>% select(mpg))

# > identical(temp1, temp2)
# [1] TRUE

Upvotes: 3

Related Questions