我们可以在逻辑向量上执行arrange(TRUE 按字母顺序在FALSE 之后)和slice 分组后的第一行
library(dplyr)
df1 %>%
arrange(Year, ID, Type == 'O') %>%
group_by(Year, ID) %>%
slice_head(n = 1) %>%
ungroup
-输出
# A tibble: 4 × 3
Year ID Type
<int> <int> <chr>
1 2000 1 R
2 2000 5 O
3 2000 8 R
4 2002 8 O
或者在arrange 之后使用distinct,它返回第一个非重复行
df1 %>%
arrange(Year, ID, Type == 'O') %>%
distinct(Year, ID, .keep_all = TRUE)
-输出
Year ID Type
1 2000 1 R
2 2000 5 O
3 2000 8 R
4 2002 8 O
数据
df1 <- structure(list(Year = c(2000L, 2000L, 2000L, 2000L, 2000L, 2000L,
2000L, 2000L, 2000L, 2002L), ID = c(1L, 1L, 1L, 1L, 1L, 5L, 5L,
8L, 8L, 8L), Type = c("O", "O", "O", "O", "R", "O", "O", "R",
"O", "O")), class = "data.frame", row.names = c(NA, -10L))