这里有一个在base R
中的选项。
lst1 <- split(df$ind, df$year)
lst1[] <- lengths(Reduce(function(x, y) y[!x %in% y],
split(df$ind, df$year), accumulate = TRUE))
setNames(stack(lst1)[2:1], c('year', 'n'))
如果这涉及到所有之前的“年份”
lst1 <- split(df$ind, df$year)
lst2 <- vector('list', length(lst1))
names(lst2) <- names(lst1)
lst2[[1]] <- length(lst1[[1]])
for(i in 2:length(lst1)) lst2[[i]] <- sum(!lst1[[i]] %in%
unlist(lst1[seq_len(i-1)]))
setNames(stack(lst2)[2:1], c('year', 'n'))
或者使用
dplyr
中的一个选项,按 'year' 进行
arrange
,获取唯一的行(假设在一个 'year' 内不会有重复的 'ind'),然后使用
count
。
library(dplyr)
df %>%
arrange(year) %>%
distinct(ind, .keep_all = TRUE) %>%
select(-n) %>%
count(year)
数据
df <- structure(list(ind = c(67L, 76L, 95L, 171L, 60L, 73L, 95L, 171L,
175L, 60L, 95L, 96L, 99L, 171L, 171L, 172L, 178L), year = c(2016L,
2016L, 2016L, 2016L, 2017L, 2017L, 2017L, 2017L, 2017L, 2018L,
2018L, 2018L, 2018L, 2018L, 2019L, 2019L, 2019L), n = c(1L, 1L,
2L, 3L, 1L, 1L, 3L, 1L, 1L, 4L, 7L, 1L, 1L, 1L, 2L, 1L, 1L)),
class = "data.frame", row.names = c(NA,
-17L))