您可以使用is.na <-
和cumsum
传播NA
值:
df <- within(df, Y <- ave(Y, id, FUN = function(x) { is.na(x) <- is.na(cumsum(x)) x })) df[order(df$id),] # id Y X t # 1 1 1 5 1 # 5 1 NA 3 2 # 9 1 NA 8 3 # 13 1 NA 3 4 # 2 2 1 6 1 # 6 2 1 5 2 # 10 2 1 9 3 # 14 2 0 4 4 # 3 3 0 7 1 # 7 3 NA 6 2 # 11 3 NA 1 3 # 15 3 NA 5 4 # 4 4 1 8 1 # 8 4 1 7 2 # 12 4 NA 2 3 # 16 4 NA 6 4