3

I met a wired problem while sapply subset to a list of dataframe inside a function that R saying "Error in eval(expr, envir, enclos) : object 'thresh' not found". I wonder why this would happen.

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)
4

1 回答 1

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
于 2012-09-03T09:03:06.000 回答