【问题标题】:Using the dot operator in dplyr::bind_cols在 dplyr::bind_cols 中使用点运算符
【发布时间】:2017-12-14 21:46:32
【问题描述】:

我发现 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

感谢您的帮助。

【问题讨论】:

  • @markdly 如果您使用mtcars %&gt;% bind_cols(select(., -mpg), select(., mpg)) 检查您的解决方案,则结果不正确。它只是将 bind_cols 应用于 mtcar 的 2 个副本。即选择被忽略
  • 哎呀!是的,你是对的

标签: r dplyr nse


【解决方案1】:

您需要使用 {} 包装您的函数,以便将 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 %&gt;% {bind_cols(. %&gt;% select(-mpg), . %&gt;% select(mpg))} 仍然失败,Error in cbind_all(x) : STRING_ELT() can only be applied to a 'character vector', not a 'NULL' 。想法?
  • @Taran 是的,不太清楚为什么这不起作用。我的解决方案虽然打字少。
  • 真的!不过很好奇。感谢您提供正确的解决方案!
【解决方案2】:

另一种解决方案:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-12
    • 2015-02-07
    • 1970-01-01
    • 1970-01-01
    • 2015-11-16
    • 2018-07-03
    相关资源
    最近更新 更多