在
data.table
中,我们拥有
rleid
函数,这使得这里变得简单。
library(data.table)
setDT(df)[, seq1 := seq_len(.N), .(ID, rleid(loc))]
df
我们可以在dplyr
和基础R方法中使用rleid
来获得预期的输出。
library(dplyr)
df %>%
group_by(ID, grp = data.table::rleid(loc)) %>%
mutate(seq1 = row_number())
或者使用基本R语言:
df$seq1 <- with(df, ave(yr, ID, data.table::rleid(loc), FUN = seq_along))
@chinsoon12提出的简洁选项是使用
rowid
函数。
setDT(df)[, seq2 := rowid(ID, rleid(loc))]
数据
df <- structure(list(ID = c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L,
3L, 3L, 3L, 3L, 3L), yr = c(1990L, 1991L, 1992L, 1993L, 1994L,
1990L, 1991L, 1992L, 1993L, 1994L, 1990L, 1991L, 1992L, 1993L,
1994L), loc = structure(c(1L, 1L, 2L, 2L, 2L, 2L, 2L, 1L, 2L,
2L, 3L, 3L, 3L, 2L, 3L), .Label = c("A", "B", "C"), class = "factor"),
seq = c(1L, 2L, 1L, 2L, 3L, 1L, 2L, 1L, 1L, 2L, 1L, 2L, 3L,
1L, 1L)), class = "data.frame", row.names = c(NA, -15L))
data.table
中,使用setDT(df)[, seq2 := rowid(ID, rleid(loc))]
。 - chinsoon12