【发布时间】:2023-04-14 11:24:01
【问题描述】:
我很难理解如何使用{{ }} 运算符在自定义函数中传递裸变量名。将运算符与 if 子句结合使用时出现错误。
此功能有效:
f <- function(.data, .vars=NULL){
require(dplyr)
df = select(.data, {{ .vars }})
print(head(df))
}
f(iris, c(Species, Sepal.Length))
#> Loading required package: dplyr
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
#> Species Sepal.Length
#> 1 setosa 5.1
#> 2 setosa 4.9
#> 3 setosa 4.7
#> 4 setosa 4.6
#> 5 setosa 5.0
#> 6 setosa 5.4
由reprex package (v2.0.1) 于 2021 年 12 月 20 日创建
如果我尝试添加 if 子句,则会引发错误:
f <- function(.data, .vars=NULL){
require(dplyr)
if(!is.null(.vars)) df = select(.data, {{ .vars }})
else df = .data
print(head(df))
}
f(iris, c(Species, Sepal.Length))
#> Loading required package: dplyr
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
#> Error in f(iris, c(Species, Sepal.Length)): object 'Species' not found
由reprex package (v2.0.1) 于 2021 年 12 月 20 日创建
我错过了什么?
【问题讨论】: