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

5

我看到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

但不是这个。

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

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

感谢您的帮助。

1
@markdly 如果你使用 mtcars %>% bind_cols(select(., -mpg), select(., mpg)) 检查你的解决方案,结果是不正确的。它只是将 bind_cols 应用于 mtcars 的 2 个副本。即选择被忽略了。 - Taran
糟糕!是的,你说得对。 - markdly
2个回答

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

是的,这似乎做得更好。但是使用这个 mtcars %>% {bind_cols(. %>% select(-mpg), . %>% select(mpg))} 仍然会出现 Error in cbind_all(x) : STRING_ELT() can only be applied to a 'character vector', not a 'NULL' 的错误。你有什么想法吗? - Taran
@Taran 嗯,不太确定为什么这个不起作用。但我的解决方案打字更少。 - acylam
1
真的!这很有趣。感谢您提供正确的解决方案! - Taran

0

另一个解决方案:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接