I want to delete duplicates with multiple grouping conditions but always get way less results than expected.
The dataframe compares two companies per year. Like this:
| year | c1 | c2 |
|---|---|---|
| 2000 | a | b |
| 2000 | a | c |
| 2000 | a | d |
| 2001 | a | b |
| 2001 | b | d |
| 2001 | a | c |
For every c1 I want to look at c2 and delete rows which are in the previous year. I found a similar problem but with just one c. Here are some of my tries so far:
df<- df%>%
group_by(c1,c2) %>%
mutate(dup = n() > 1) %>%
group_split() %>%
map_dfr(~ if(unique(.x$dup) & (.x$year[2] - .x$year[1]) == 1) {
.x %>% slice_head(n = 1)
} else {
.x
}) %>%
select(-dup) %>%
arrange(year)
df<- sqldf("select a.*
from df a
left join df b on b.c1=a.c1 and b.c2 = a.c2 and b.year = a.year - 1
where b.year is null")
The desired output for the example would be:
| year | c1 | c2 |
|---|---|---|
| 2000 | a | b |
| 2000 | a | c |
| 2000 | a | d |
| 2001 | b | d |