删除所有列中具有相同值的行 [英] Remove rows with the same value across all columns
本文介绍了删除所有列中具有相同值的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个数据帧(df),如下所示:
Suppose I have a data frame (df) that looks like below:
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行并删除其余行).
I want to remove any rows that have the same value throughout the entire row (in the example above, I would like to keep rows 1, 3, 5, 7, 8 and remove the rest).
我已经找到了如何删除所有具有零的行
I've figured out how to remove all rows that have zeros
df$sum <- rowSums(df[,c(2:8)], na.rm = T )
df.all0 <- df[which(df$sum == 0),]
但是,这不一定适用于所有其他行.与其他问题不同,该问题要求在整个行中查找重复项,而不仅仅是特定的列.
However, this doesn't necessarily work for all the other rows. Unlike other questions, this question asks to look for duplicates across the entire row, not just specific columns.
任何帮助将不胜感激!
推荐答案
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
这篇关于删除所有列中具有相同值的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文