我正在尝试使用lazyeval
包并遇到问题。当我使用某些变量名称(例如日期,均值)作为我data.frame
中R的函数存在时,lazy
不再有效。所以我不得不重新使用substitute
。有更好的解决方法吗?
# this function has problems with certain variables
f_lazy <- function(data, variable){
variable <- lazyeval::lazy(variable)
lazyeval::lazy_eval(variable, data)
}
# these functions work
f_lazydots <- function(data, ...){
variable <- lazyeval::lazy_dots(...)[[1]]
lazyeval::lazy_eval(variable, data)
}
f_substitute <- function(data, variable){
variable <- substitute(variable)
eval(variable, data)
}
data <- data.frame(x = 1, y = "a", date = Sys.Date(), mean = 1)
f_lazy(data, x)
## [1] 1
f_lazy(data, y)
## [1] a
## Levels: a
f_lazy(data, date)
## function ()
## .Internal(date())
## <bytecode: 0x000000000cee1980>
## <environment: namespace:base>
f_lazy(data, mean)
## function (x, ...)
## UseMethod("mean")
## <bytecode: 0x000000000bc87820>
## <environment: namespace:base>
f_lazydots(data, date)
## [1] "2015-05-12"
f_lazydots(data, mean)
## [1] 1
f_substitute(data, date)
## [1] "2015-05-12"
f_substitute(data, mean)
## [1] 1