在dplyr :: bind_cols中使用点运算符

Tar*_*ran 5 r dplyr nse

我看到dplyr出现了一些意想不到的行为.我有一个特定的用例,但我会设置一个虚拟问题来说明我的观点.为什么这样做,

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
Run Code Online (Sandbox Code Playgroud)

但不是这个,

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

Error in cbind_all(x) : Argument 2 must be length 1, not 32
Run Code Online (Sandbox Code Playgroud)

谢谢您的帮助.

avi*_*seR 3

您需要将函数包装起来,{}以通过管道mtcars连接到另一个函数中的函数,如下所示:

library(dplyr)

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

# > identical(temp1, temp2)
# [1] TRUE
Run Code Online (Sandbox Code Playgroud)