2012-07-18 47 views
1

我遇到了一個莫名其妙的錯誤。 我使用下面的函數來刪除包含在任一列R應用錯誤 - as.matrix.data.frame()中的錯誤

##### 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) 
    } 
} 

該功能能正常工作正常的NA觀察的數據幀的行,例如一個可再現的例子是:

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] 

感謝響應,

+1

你可以提供一個例子,它*不*工作,而不是*工作*? – A5C1D2H2I1M1N2O1R2T1 2012-07-18 06:54:52

+0

我建議在函數的開頭插入'browser()'。這樣,你可以遍歷你的代碼,檢查每個元素並追蹤錯誤。 – 2012-07-18 08:19:58

回答

4

另一種方法來解決你的問題將是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 
+0

不錯,這不需要重新投射 – 2012-07-18 08:21:42

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

+ 1 - 明顯的做法! – mnel 2012-07-18 06:55:24

0

沒有問題數據,我只能建議不同的功能

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

hmm th anks的回覆, 不知道complete.cases功能。但這給了另一個錯誤

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

chisq.test Error Message - >似乎解決這個問題的方式。

有問題的數據框的問題是它包含一個帶日期的POSIXlt對象列。明確的完成案件和適用於內部工作並沒有很好地處理。解決方法是使用strftime轉換爲字符,然後使用strptime轉換回來。

感謝,

1

一般情況下,如果你沒有吶在你的數據,然後根據阿迪亞Sihag建議,該問題可能是一個data.frame列的數據類型可能是列表或POSIXlt對象等對象列表。您可以投射它們,也可以僅在列上使用樂器。但是,在應用lapply之前,再次確保您的列數據類型不是列表或POSIXlt,如果是,則只需投射它。