我想简单地生成一个变量来计算个人当前得分的前几年数.
例如,如果我们从这个可重复的例子中查看personID
set.seed(987)
mydata <- data.frame(
personID = rep(c(1:10), each = 10),
year= rep(c(1991:2000), each = 1),
score = sample(c(0, 1, 2), 100, replace = TRUE)
)
Run Code Online (Sandbox Code Playgroud)
这是personI == 5
personID year score
5 1991 2
5 1992 1
5 1993 0
5 1994 0
5 1995 0
5 1996 0
5 1997 2
5 1998 0
5 1999 1
5 2000 1
Run Code Online (Sandbox Code Playgroud)
我想要生成的是变量Z,它应该是这样的
personID year score Z
5 1991 2 0
5 1992 1 0 …Run Code Online (Sandbox Code Playgroud)