我遇到了一个有线问题,而 sapply subset 到一个函数内的数据框列表中,R说“ eval中的错误(expr,envir,enclos) :找不到对象'thresh'“。我想知道为什么会这样。
test<-list()
test[[1]]<-as.data.frame(matrix(rnorm(50*5,10,100),50,5))
test[[2]]<-as.data.frame(matrix(rnorm(50*5,10,100),50,5))
findmax<-function(test,thresh){
print(thresh)
max(unlist(sapply(test,subset,V1>thresh,select=c("V1"))))
}
findmax(test,thresh=10)
答案 0 :(得分:3)
请注意?subset
中的警告:
Warning:
This is a convenience function intended for use interactively.
For programming it is better to use the standard subsetting
functions like ‘[’, and in particular the non-standard evaluation
of argument ‘subset’ can have unanticipated consequences.
subset
有一些奇怪的评估规则,它在哪里查找其中的对象和变量,这取决于调用环境等。当用户在顶级交互式调用时这些工作正常,但在包装时经常失败你发现的内部功能。
以下是使用标准子集重写函数的一种方法:
findmax <- function(test, thresh, want) {
foo <- function(x, thresh, want) {
take <- x[, want] > thresh
x[take, want]
}
max(unlist(sapply(test, foo, thresh = thresh, want = want)))
}
findmax(test, thresh = 10, want = "V1")
为您的测试数据提供:
R> findmax(test, thresh = 10, want = "V1")
[1] 230.9756