R apply error - as.matrix.data.frame()中的错误

Adi*_*hag 1 r apply

我遇到了一个莫名其妙的错误.我正在使用以下函数删除任何列中包含NA观察的数据帧的行

##### removes NA'd rows from a dataFrame
wipeNArows<-function(X){
  rowsToDelete<-unique(unlist(apply(apply(X,2,is.na),2,which)))
  if (length(rowsToDelete)>0){
    return (X[-rowsToDelete,])
  }
  else{
    return (X)
  }
}
Run Code Online (Sandbox Code Playgroud)

此功能正常工作,例如可重现的示例是:

testFrame<-data.frame(x=rpois(20,10),y=rpois(20,10),z=rpois(20,10))
rowsToDelete<-sample(1:nrow(testFrame),5,FALSE)
testFrame$x[rowsToDelete]<-NA
testFrame
wipeNArows(testFrame) ### removes the rows where NA is encountered
Run Code Online (Sandbox Code Playgroud)

现在我有一个包含大约2993行的数据框.当我通过函数传递此数据框时,我面临以下错误:

Error in apply(apply(X, 2, is.na), 2, which) : 
error in evaluating the argument 'X' in selecting a method for function 'apply': Error in as.matrix.data.frame(X) : 
dims [product 14965] do not match the length of object [14974]
Run Code Online (Sandbox Code Playgroud)

谢谢你的回复,

joh*_*nes 8

对我来说很好,但为什么不使用 ?complete.cases

testFrame[complete.cases(testFrame),]
    x  y  z
2  10  8 13
3  11 16 18
4  11  7  7
6   8  8 14
7   9 11 11
8  12 11  5
9  10  7  4
10  7 12  9
11 10 13 11
12  9 12 10
13 10  5  8
14 13  5  8
15 11  5  5
18 13 14  7
19  2 13  8

identical(testFrame[complete.cases(testFrame),], wipeNArows(testFrame))
[1] TRUE
Run Code Online (Sandbox Code Playgroud)