我有一个数据集我想删除4个不同列中包含重复信息的数据行。
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-6列删除任何具有重复数据的行。因此,如果正确完成,将仅删除第4行和第1行,基于所有Y变量完全相同。它是一个多列条件。
我相信我很接近,但它的工作正常。
我试过了:new = foo[!(duplicated(foo[,1:6]))]
想要使用它会搜索的重复命令,只找到那些完全匹配的命令?
我考虑过使用&amp;的条件语句,但也无法弄清楚如何做到这一点
new = foo[foo$y1==foo$y2|foo$y3|foo$y4|foo$y5|foo$y6]
我想到了哪个但是我现在不堪重负并迷失了。我希望foo看起来像:
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
答案 0 :(得分: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 :(得分:2)
foo[apply(foo, 1, function(x) any(x != x[1])),]
答案 2 :(得分: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