【问题标题】:R apply error - error in as.matrix.data.frame()R应用错误 - as.matrix.data.frame() 中的错误
【发布时间】:2012-07-18 06:47:14
【问题描述】:

我遇到了一个莫名其妙的错误。 我正在使用以下函数删除任何列中包含 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)
  }
}

这个函数可以正常工作,例如一个可重现的例子是:

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

现在我有一个包含大约 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]

感谢您的回复,

【问题讨论】:

  • 你能提供一个例子,它工作,而不是一个工作
  • 我建议在函数的开头插入browser()。这样,您就可以单步执行您的代码,检查每个元素并找出错误。

标签: r apply


【解决方案1】:

对我来说很好,但为什么不使用?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

【讨论】:

    【解决方案2】:

    解决问题的另一种方法是na.omit

    na.omit(testFrame)
    
        x  y  z
    2   7 11 11
    3  12 10 10
    4  13 10  9
    6  11 10 12
    7  13 14  8
    8   7  9  7
    9   8 11 12
    10  5 10  7
    11  5 15  9
    12  7 13  9
    15 15  8  9
    16 13  7 15
    17  5 10 12
    18  9  8  6
    20 18  7  6
    

    【讨论】:

    • 不错,不需要重播
    【解决方案3】:

    嗯,谢谢您的回复, 不知道 complete.cases 功能。但这又给出了另一个错误

     Error in complete.cases(dFrame) : not all arguments have the same length
    

    chisq.test Error Message --> 似乎以某种方式解决了这个问题。

    有问题的数据框的问题在于它包含一个带有日期的 POSIXlt 对象列。显然 complete.cases 和 apply 内部工作并没有很好地处理这个问题。解决方法是使用 strftime 强制转换为字符,然后使用 strptime 返回。

    谢谢,

    【讨论】:

      【解决方案4】:

      一般情况下,如果您的数据中没有 na,​​那么正如 Aditya Sihag 建议的那样,问题可能出在您的 data.frame 列的数据类型之一可能是对象列表,例如列表或 POSIXlt 对象。您可以投射它们,也可以仅在列上使用 lapply。但在应用 lapply 之前再次确保您的列数据类型不是列表或 POSIXlt,如果是,则只需转换它。

      【讨论】:

        【解决方案5】:

        没有问题数据,我只能建议不同的功能

        wipe_na_rows <- function(X){
          X[!apply(X, 1, function(x) any(is.na(x))),]
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2023-02-08
          • 1970-01-01
          • 1970-01-01
          • 2013-05-31
          • 1970-01-01
          • 2013-10-31
          • 2014-12-14
          • 2023-02-04
          相关资源
          最近更新 更多