2017-06-06 74 views
1

假設我有一個數據幀(DF),看起來像如下:所有列刪除具有相同值的行

options(stringsAsFactors = F) 

cars <- c("Car1", "Car2", "Car3", "Car4", "Car5", "Car6", "Car7", "Car8", "Car9") 
test1 <- c(0,0,3,1,4,2,1,3,0) 
test2 <- c(0,0,2,1,0,2,2,5,0) 
test3 <- c(1,0,5,1,2,2,6,7,0) 
test4 <- c(2,NA,2,1,2,2,1,1,0) 
test5 <- c(0,0,1,1,0,2,1,3,0) 
test6 <- c(1,0,1,1,1,2,3,4,0) 
test7 <- c(3,0,2,1,0,2,1,1,0) 

df <- data.frame(cars,test1,test2,test3,test4,test5,test6,test7) 

#df 
    cars test1 test2 test3 test4 test5 test6 test7 
#1 Car1  0  0  1  2  0  1  3 
#2 Car2  0  0  0 NA  0  0  0 
#3 Car3  3  2  5  2  1  1  2 
#4 Car4  1  1  1  1  1  1  1 
#5 Car5  4  0  2  2  0  1  0 
#6 Car6  2  2  2  2  2  2  2 
#7 Car7  1  2  6  1  1  3  1 
#8 Car8  3  5  7  1  3  4  1 
#9 Car9  0  0  0  0  0  0  0 

我想刪除具有在整個行相同值的任何行(在上面的例子中,我想保留第1,3,5,7,8行並刪除其餘部分)。

我已經想通了如何刪除具有零

df$sum <- rowSums(df[,c(2:8)], na.rm = T) 
df.all0 <- df[which(df$sum == 0),] 

所有行然而,這並不一定對所有其他行工作。與其他問題不同,此問題要求在整個行中查找重複內容,而不僅僅是特定的列。

任何幫助將不勝感激!

+0

@akaDrHouse我看不出我的問題是如何重複的。我在詢問整行,而不是列中的重複。 – Sheila

+0

你是對的;我誤解了。對於那個很抱歉。 – akaDrHouse

回答

4
keep <- apply(df[2:8], 1, function(x) length(unique(x[!is.na(x)])) != 1) 
df[keep, ] 

    cars test1 test2 test3 test4 test5 test6 test7 
1 Car1  0  0  1  2  0  1  3 
3 Car3  3  2  5  2  1  1  2 
5 Car5  4  0  2  2  0  1  0 
7 Car7  1  2  6  1  1  3  1 
8 Car8  3  5  7  1  3  4  1 
+0

Hi @JasonWang!保存已刪除行的汽車ID的最佳方法是什麼? – Sheila

+0

'which(!keep)'會給你你刪除的行索引。 – JasonWang

5

這是rowSums的選項;邏輯是檢查是否有來自您感興趣的一列是行不同行(NA不計)中的任何值:

df[rowSums(df[-1] != df[[2]], na.rm = TRUE) != 0,] 

# cars test1 test2 test3 test4 test5 test6 test7 
#1 Car1  0  0  1  2  0  1  3 
#3 Car3  3  2  5  2  1  1  2 
#5 Car5  4  0  2  2  0  1  0 
#7 Car7  1  2  6  1  1  3  1 
#8 Car8  3  5  7  1  3  4  1 
+0

嗨!謝謝你的想法。我對你的邏輯有點困惑。你是說你在比較test1列的所有列嗎? – Sheila

+0

哦等等!我想我明白。您正在使用test1作爲參考點來檢查所有其他列是否具有相同的值(或不是)。對? – Sheila

+0

是檢查所有* test *列對* test1 *,如果有一個列的非NA值不同,則rowSums將與零不同,因此您將保留它。 – Psidom

0

我們還可以用MapReduce

df[c(Reduce(`+`, Map(function(x,y) x != y & !is.na(x), df[-1], list(df[2]))) != 0),] 
# cars test1 test2 test3 test4 test5 test6 test7 
#1 Car1  0  0  1  2  0  1  3 
#3 Car3  3  2  5  2  1  1  2 
#5 Car5  4  0  2  2  0  1  0 
#7 Car7  1  2  6  1  1  3  1 
#8 Car8  3  5  7  1  3  4  1 
相關問題