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)
Do heed the Warning in
?subset:subsethas some strange evaluation rules as to where it looks for objects and variables therein, which depend upon calling environments etc. These work fine when called by the user interactively at the top level, but often fail when wrapped inside functions as you have found.Here is one way to rewrite the function using standard subsetting:
which for your test data gives: