2012-09-14 136 views
6

我有一個數據集我想刪除4個不同列中有重複信息的數據行。然後根據r中多個列的條件刪除重複的行

foo<- data.frame(g1 = c("1","0","0","1","1"), v1 = c("7","5","4","4","3"), v2 = c("a","b","x","x","e"), y1 = c("y","c","f","f","w"), y2= c("y","y","y","f","c"), y3 = c("y","c","c","f","w"), y4= c("y","y","f","f","c"), y5=c("y","w","f","f","w"), y6=c("y","c","f","f","w")) 

foo的樣子:

g1 v1 v2 y1 y2 y3 y4 y5 y6 
1 1 7 a y y y y y y 
2 0 5 b c y c y w c 
3 0 4 x f y c f f f 
4 1 4 x f f f f f f 
5 1 3 e w c w c w w 

現在,我想刪除已經重複的基礎上,Y1-6columns數據的任何一行。所以,如果正確完成,只有第4行和第1行將被刪除,基於所有Y變量完全相同。它是一個多列條件。

我相信我很接近,但它只是工作不正常。

我曾嘗試過:new = foo[!(duplicated(foo[,1:6]))] 想用重複的命令,它會搜索,只發現那些完全匹配?

我想過使用條件語句&,但無法弄清楚如何做到這一點。
new = foo[foo$y1==foo$y2|foo$y3|foo$y4|foo$y5|foo$y6]

我想過哪些,但我現在不知所措,失去了。我希望富的樣子:

g1 v1 v2 y1 y2 y3 y4 y5 y6 
2 0 5 b c y c y w c 
3 0 4 x f y c f f f 
5 1 3 e w c w c w w 

回答

10
> foo[apply(foo[ , paste("y", 1:6, sep = "")], 1, 
      FUN = function(x) length(unique(x)) > 1), ] 
    g1 v1 v2 y1 y2 y3 y4 y5 y6 
2 0 5 b c y c y w c 
3 0 4 x f y c f f f 
5 1 3 e w c w c w w 
+1

我最喜歡的爲止。 –

+0

我很抱歉我簡化了我的例子,因爲我有更多的信息欄......所以基於變量1-6只有9條信息總欄。我將編輯上面的例子 – Kerry

+0

我更新了我的答案。現在,行的選擇基於列y1 - y6。 –

2
foo[apply(foo, 1, function(x) any(x != x[1])),] 
1
> foo[ !rowSums(apply(foo[2:6], 2, "!=", foo[1]))==0, ] 
    y1 y2 y3 y4 y5 y6 
2 c y c y w c 
3 f y c f f f 
5 w c w c w w 

> foo[ ! colSums(apply(foo, 1, duplicated, foo[1])) == 5, ] 
    y1 y2 y3 y4 y5 y6 
2 c y c y w c 
3 f y c f f f 
5 w c w c w w