使用日期变量进行延迟评估的解决方法

时间:2015-05-12 09:01:59

标签: r lazy-evaluation

我正在尝试使用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

0 个答案:

没有答案