用到的数据sample_df<-data.frame(a=1:5, b=5:1, c=c(5,3,1,4,1))
在《高级R语言编程》中非标准计算的部分,有一个相当于subset的函数
subset2<-function(x,condition){
condition_call<-substitute(condition)
r<-eval(condition_call,x,parent.frame())
x[r,]
}
此函数执行效果如下:
subset2(sample_df,a>=4)
#> a b c
#>4 4 2 4
#>5 5 1 1
然后提到非标准计算在交互编程中方便,但是在非交互中,可能会存在问题。并举了一个例子。就是对某数据取子集,然后随机对行进行排序。
subset2<-function(x,condition){
condition_call<-substitute(condition)
r<-eval(condition_call,x,parent.frame())
x[r,]
}
scramble<-function(x) x[sample(nrow(x)),]
subscramble<-function(x,condition){
scramble(subset2(x,condition))
}
然后运行subscrambl(sample_df,a>=4)
报错,提示对像a不在在。
debugonce(subset2)
subscramble(sample_df,a>=4)
#> debugging in :subset2(x,condition)
#> debug at #1:{
#> condition_call<-substitute(condition)
#> r<-eval(condition_call,x,parent.frame())
#> x[r,]
#>}
n
#> debug at #2: condition_call<-substitute(condition)
n
#> debug at #3: r<-eval(condition_call,x,parent.frame())
r<-eval(condition_call,x,parent.frame())
#> Error in eval(expr,envir,enclos):object "a" not found
condition_call
#> condition
eval(condition_call,x)
#> Error in eval(expr,env,enclos):object "a" not found
Q
文后有一句话:
找到问题了吗?condition_call包含表达式condition。因此,当我们对condition_call进行计算时,也会对condition(a>=4)进行计算。但是这个计算是不能正常完成的,因为在父环境中没有称为a的对象。但是,如果在全局环境中存在对象……
我一直没研究懂,执行到eval(condition_call,x,parent.frame())
时,这个就是要执行condition啊,而且是在数据框x中执行,为啥要说在父环境 中没有称为a的对象啊?
搞不懂。
原文见:http://adv-r.had.co.nz/Computing-on-the-language.html
好几天没人答复,其它群也没人解答,最后终于在本论坛2014年七月的一篇贴子中找到了理解的思路。【终于贯彻了谢大神的“论码农的自我修养”】的观点。