【发布时间】:2023-01-26 03:24:07
【问题描述】:
我正在尝试创建一个有条件地使用参数的函数,该参数在使用时是 df 的一列。
这是一个示例函数:
new_fx <- function(data, x, y, z=NULL){
x <- ensym(x)
y <- ensym(y)
if ( !is.null(z)){
z <- ensym(z)
}
print(head(data[[x]]))
print(head(data[[y]]))
if (!is.null(z)){
print(z)
}
}
当z离开NULL时,我希望函数忽略z。但是,当任何列作为 z 传递时,我希望它被 z<- ensym(z) 转换为符号。
这是当我尝试使用上面的函数时发生的情况:
new_fx(data=iris, x=Species, y=Petal.Width)
# [1] setosa setosa setosa setosa setosa setosa
# Levels: setosa versicolor virginica
# [1] 0.2 0.2 0.2 0.2 0.2 0.4
当 z 离开 NULL 时,一切看起来都很好。
但是当传递任何其他参数时:
new_fx(data=iris, x=Species, y=Petal.Width, z=Petal.Length)
# Error in new_fx(data = iris, x = Species, y = Petal.Width, z = Petal.Length) :
# object 'Petal.Length' not found
出于某种原因,当在条件语句中使用 ensym() 调用时,该函数会出现问题。
有什么建议么?
【问题讨论】: