[英]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))
但具有不同的數據集和不同的變量名稱。 我可以重用代碼並替換mtcars
、 cyl
和hp
。 但我寧願把它全部包裝在一個函數中
在這種情況下非常簡單,因為您可以使用 ...
f <- function(data, ...) {
data %>% select(...)
}
f(df, col1, col2)
#> col1 col2
#> 1 1 a
#> 2 2 b
#> 3 3 c
在更一般的情況下,您有兩種選擇:
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.