简体   繁体   English

将函数参数传递给 dplyr select

[英]passing function argument to dplyr select

To select a couple columns from a dataframe I can do要从数据框中选择几列我可以做

require(dplyr)
require(magrittr)

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

df %>%
  select(col1, col2)

I want to write a function similar to我想写一个类似于

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

But running f(df, col1, col2) gives me the error但是运行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)
})()

EDIT -- slightly less trivial example:编辑——稍微不那么简单的例子:

Suppose I wanted to do假设我想做

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

but with different datasets and different variable names.但具有不同的数据集和不同的变量名称。 I could reuse the code and replace mtcars , cyl , and hp .我可以重用代码并替换mtcarscylhp But I'd rather wrap it all up in a function但我宁愿把它全部包装在一个函数中

It's pretty simple in this case, since you can just use ...在这种情况下非常简单,因为您可以使用 ...

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

f(df, col1, col2)

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

In the more general case, you have two options:在更一般的情况下,您有两种选择:

  1. Wait until https://github.com/hadley/dplyr/issues/352 is closed等到https://github.com/hadley/dplyr/issues/352关闭
  2. Construct the complete expression using substitute() and then eval()使用substitute()eval()构造完整的表达式

Since rlang version 0.4.0, the curly-curly {{ operator would be a better solution.从 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