2012-09-03 34 views
3

列表我遇到了一個有線的問題,同時sapply子集到一個函數內部數據幀列表的R說:「在EVAL 錯誤的函數傳遞參數不能被發現(expr,envir,enclos):找不到對象'thresh'「。我想知道爲什麼會發生。爲什麼當sapply子集到數據幀的R中

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) 

回答

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 
+0

謝謝您的回答。 – Gahoo