我有一系列以ID表示的个人,这些ID按顺序与地址关联.其中一些人(但不是所有人)的地址带有正匹配码(匹配码=1).我想删除匹配码之前的所有地址,保留匹配码为正的地址,保留匹配码之后的地址.我还想保留所有的地址,如果这个人没有一个积极的匹配代码.因此,从这个虚拟数据:
ID = c("id1", "id1", "id1", "id2", "id2", "id2", "id3", "id3", "id3", "id4", "id4", "id4")
matchcode = c(0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0)
address = c("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l")
df = data.frame(ID, matchcode, address)
df <- df %>% group_by(ID) %>% mutate(order = row_number()) %>% ungroup
我想得到这个:
ID matchcode address order
<chr> <dbl> <chr> <int>
1 id1 0 a 1
2 id1 1 b 2
3 id2 0 d 1
4 id2 0 e 2
5 id2 1 f 3
6 id3 0 g 1
7 id3 0 h 2
8 id3 0 i 3
9 id4 1 j 1
任何帮助都将不胜感激.