所有列删除具有相同值的行
问题描述:
假设我有一个数据帧(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),]
所有行然而,这并不一定对所有其他行工作。与其他问题不同,此问题要求在整个行中查找重复内容,而不仅仅是特定的列。
任何帮助将不胜感激!
答
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
答
这是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
答
我们还可以用Map
与Reduce
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
@akaDrHouse我看不出我的问题是如何重复的。我在询问整行,而不是列中的重复。 – Sheila
你是对的;我误解了。对于那个很抱歉。 – akaDrHouse