[英]Iterating through all rows in R, removing those that fit criteria
R數據幀。 它有大約十幾列和150行左右。 在這兩個條件下,我想遍歷每一行並將其刪除
我的代碼看起來像這樣,但它一直在崩潰。 這是一個愚蠢的錯誤,但我無法弄清楚。
for (i in 2:nrow(newfile)){
if (is.na(newfile[i,8]) && !is.na(newfile[(i-1),8]){
newfile<-newfile[-i,]
}
}
顯然在這個例子中,newfile是我的數據幀。
我得到的錯誤
[.data.frame
(newfile,-i,)中出錯:找不到對象'i'
問題解決了,但是如果你們想要搗亂,一些測試數據:
23 L8 29141078 744319 27165443
24 L8 27165443 NA NA
25 L8 28357836 8293 25116398
26 L8 25116398 NA NA
27 L8 28357836 21600 25116398
28 L8 25116398 NA NA
29 L8 40929564 NA NA
30 L8 40929564 NA NA
31 L8 41917264 33234 39446503
32 L8 39446503 NA NA
33 L8 41917264 33981 39446503
34 L8 39446503 NA NA
顯然這里有一點修改,所以現在你要比較第4列和它上面的第4列(或者你可以使用第5列,無論哪種方式)
問題是你正在從自己身下改變數據框; nrow(newfile)
的原始評估不會隨着你的進展而更新(如果你有一個C風格的循環for (i=1; i<=nrow(newfile); i++)
...)。 另一方面,在while
循環中,每次循環都會重新評估條件,所以我認為這樣可行。
i <- 2
while (i<=nrow(newfile)){
if (is.na(newfile[i,8]) && !is.na(newfile[i-1,8])) {
newfile<-newfile[-i,]
}
i <- i+1
}
您沒有給我們一個容易重現的答案(即帶答案的測試數據集),所以我現在不打算對此進行測試。
仔細思考(我現在沒時間給出這個)可能會導致非迭代(因此可能非常快,如果重要的話)這樣做。
嗯,如果我這樣做,我明白了
Error in if (is.na(newfile[i,8]) && !is.na(newfile[(i-1),8]) { :
missing value where TRUE/FALSE needed
這是因為你在迭代它時刪除行,所以當你得到nrow(newfile)
(這是行的原始行數,因為nrow(newfile)
在開始時被計算一次。 foor loop),它可能不再存在,因為行已被刪除。
您可以通過構造要保留哪些行的邏輯索引來完全避免循環(即長度為nrow(newfile)
向量,如果要保留行,則為TRUE
,否則為FALSE
):
n <- nrow(newfile)
# first bit says "is the row NA (for rows 2:n)"
# second bit says "is the row above *not* NA (for rows 1:(n-1))
# the & finds rows satisfying *both* conditions (first row always gets kept)
toRemove <- c(FALSE,is.na(newfile[-1,8])) & c(FALSE,!is.na(newfile[-n,8]))
toKeep <- !toRemove
newfile <- newfile[toKeep,]
你可以在一行中完成這一切,如果這是你的事情:
newfile <- newfile[ !(c(FALSE,is.na(newfile[-1,8])) & c(FALSE,!is.na(newfile[-nrow(newfile),8]))), ]
這是另一種解決方案。 但如果前一個值也是NA,它會保留NA值。
#create some dummy data
newfile <- matrix(runif(800), ncol = 8)
newfile[rbinom(100, 1, 0.25) == 1, 8] <- NA
#the selection
newfile[-which(diff(is.na(newfile[, 8])) == 1) - 1, ]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.