繁体   English   中英

将函数参数传递给 dplyr select

[英]passing function argument to dplyr select

要从数据框中选择几列我可以做

require(dplyr)
require(magrittr)

df <- data.frame(col1=c(1, 2, 3), col2=letters[1:3], col3=LETTERS[4:6])

df %>%
  select(col1, col2)

我想写一个类似于

f <- function(data, firstCol, secondCol){
   data %>%
    select(substitute(firstCol), substitute(secondCol))
}

但是运行f(df, col1, col2)给了我错误

Error in select_vars(names(.data), ..., env = parent.frame()) : 
  (list) object cannot be coerced to type 'double'
Called from: (function () 
{
    .rs.breakOnError(TRUE)
})()

编辑——稍微不那么简单的例子:

假设我想做

mtcars %>%
  select(cyl, hp) %>%
  unique %>%
  group_by(cyl) %>%
  summarise(avgHP = mean(hp))

但具有不同的数据集和不同的变量名称。 我可以重用代码并替换mtcarscylhp 但我宁愿把它全部包装在一个函数中

在这种情况下非常简单,因为您可以使用 ...

f <- function(data, ...) {
  data %>% select(...)
}

f(df, col1, col2)

#>   col1 col2
#> 1    1    a
#> 2    2    b
#> 3    3    c

在更一般的情况下,您有两种选择:

  1. 等到https://github.com/hadley/dplyr/issues/352关闭
  2. 使用substitute()eval()构造完整的表达式

从 rlang 版本 0.4.0 开始,curly-curly {{运算符将是更好的解决方案。

f <- function(data, firstCol, secondCol){
   data %>%
    select({{ firstCol }}, {{ secondCol }})
}

df <- data.frame(col1=c(1, 2, 3), col2=letters[1:3], col3=LETTERS[4:6])

df %>% f(col1, col2)

#   col1 col2
# 1    1    a
# 2    2    b
# 3    3    c

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM