[英]How to remove specific duplicates in R
我有以下数据:
> head(bigdata)
type text
1 neutral The week in 32 photos
2 neutral Look at me! 22 selfies of the week
3 neutral Inside rebel tunnels in Homs
4 neutral Voices from Ukraine
5 neutral Water dries up ahead of World Cup
6 positive Who's your hero? Nominate them
我的副本将如下所示( $type
为空):
7 Who's your hero? Nominate them
8 Water dries up ahead of World Cup
我这样删除重复项:
bigdata <- bigdata[!duplicated(bigdata$text),]
问题是,它删除了错误的重复项。 我想删除$type
为空的那个,而不是$type
有值的那个。
如何删除R中的特定重复项?
所以这是不使用duplicated(...)
的解决方案。
# creates an example - you have this already...
set.seed(1) # for reproducible example
bigdata <- data.frame(type=rep(c("positive","negative"),5),
text=sample(letters[1:10],10),
stringsAsFactors=F)
# add some duplicates
bigdata <- rbind(bigdata,data.frame(type="",text=bigdata$text[1:5]))
# you start here...
newdf <- with(bigdata,bigdata[order(text,type,decreasing=T),])
result <- aggregate(newdf,by=list(text=newdf$text),head,1)[2:3]
这将按文本和类型按降序对bigdata
进行排序,以便对于给定的文本,空type
将出现在任何非空type
。 然后,我们仅提取每个text
的每种类型的第一个匹配项。
如果您的数据确实“很大”,那么data.table
解决方案可能会更快。
library(data.table)
DT <- as.data.table(bigdata)
setkey(DT, text, type)
DT.result <- DT[, list(type = type[.N]), by = text]
这样做基本上是一样的,但是由于setkey
仅按setkey
排序,因此我们使用type[.N]
来获取每个text
的type
的最后一次出现。 .N
是一个特殊变量,用于保存该组的元素数。
请注意,当前的开发版本实现了setorder()
函数,该data.table
通过引用对data.table
进行排序,并且可以按data.table
和降序进行排序。 因此,使用开发版本 ,它将是:
require(data.table) # 1.9.3
setorder(DT, text, -type)
DT[, list(type = type[1L]), by = text]
foo = function(x){
x == ""
}
bigdata <- bigdata[-(!duplicated(bigdata$text)&sapply(bigdata$type, foo)),]
您应该保留不重复或不缺少类型值的行。 duplicated
函数仅返回每个值的第二个和以后的重复项(签出duplicated(c(1, 1, 2))
fromLast=TRUE
duplicated(c(1, 1, 2))
),因此我们需要使用该值和使用fromLast=TRUE
调用的duplicated
值。
bigdata <- bigdata[!(duplicated(bigdata$text) |
duplicated(bigdata$text, fromLast=TRUE)) |
!is.na(bigdata$type),]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.