【发布时间】:2017-04-29 21:41:02
【问题描述】:
我喜欢使用字符输入来创建 dplyr 函数,因此对即将推出的新 v0.6.0 感到非常高兴。
为了好玩和学习当前 dplyr 版本 0.5.0.9004,我尝试制作一个可以接受字符参数和表达式 (NSE) 的灵活函数。
我确实成功了,但这不能做得更优雅吗?!
d = data.frame(v1=1:2, v2=9:8)
fixquo <- function(x){
# 'fixquo' expects a enquo-ed object, then sees if enquo-ing needs to be 'reversed'...
if(!length(tryCatch({ls(get_env(x))}, error=function(e) "empty")))
x = as.name(as.character(UQ(x))[2])
x
}
Dtest <- function(d, x="v1", res="z"){
x <- enquo(x) %>% fixquo()
d %>% mutate(!!res := UQ(x))
}
Dtest(d)
Dtest(d, "v1")
Dtest(d, v1)
Dtest(d, v2)
【问题讨论】:
-
什么是enquo?是从包裹里拿出来的吗?
-
dplyr 包!来自 github 上 tidyverse/dplyr 的新开发者版本,将于 2017 年 5 月晚些时候上线。
-
您能否显示预期的输出,因为某些调用正在获取我的字符串,即
Dtest(d, "v1")# v1 v2 z 1 1 9 v1 2 2 8 v1