删除R中组之间的重复项
在此先感谢您的帮助。我的数据如下所示:
|year|class|
|---|----|
|2007|a|
|2007|b|
|2007|c|
|2007|d|
|2008|a|
|2008|b|
|2008|e|
|2008|f|
|2009|c|
|2009|d|
|2009|e|
|2009|g|
目标是删除前一年发生的任何类,因此最终数据如下所示:
|year|class|
|---|----|
|2007|a|
|2007|b|
|2007|c|
|2007|d|
|2008|e|
|2008|f|
|2009|c|
|2009|d|
|2009|g|
我试过这段代码,我打算对数据进行分组,然后删除组内的所有重复项,但它并没有删除几行的所有内容。我还尝试了 unique() 而不是重复(),但它不起作用。
d %>% group_by(class, Group = c(0, cumsum(diff(year) != 1))) %>%
filter(!(duplicated(class, fromLast = TRUE)| duplicated(class))) %>%
ungroup() %>%
select(-Group)
是否有另一个 R 函数可以查看组差异?谢谢你的帮助
编辑:也感谢大家非常有帮助的答案!
回答
左将 DF 在类上与自身连接,年差为 1,并仅保留没有此类匹配的那些行。
library(sqldf)
sqldf("select a.*
from DF a
left join DF b on b.class = a.class and b.year = a.year - 1
where b.year is null")
给予:
year class
1 2007 a
2 2007 b
3 2007 c
4 2007 d
5 2008 e
6 2008 f
7 2009 c
8 2009 d
9 2009 g
笔记
Lines <- "|year|class|
|2007|a|
|2007|b|
|2007|c|
|2007|d|
|2008|a|
|2008|b|
|2008|e|
|2008|f|
|2009|c|
|2009|d|
|2009|e|
|2009|g|"
DF <- read.table(text = Lines, sep = "|", header = TRUE)[2:3]