First off, for future posts please provide reproducible and copy&paste-able sample data; we cannot extract data from screenshots. For details see how to provide a minimal reproducible example/attempt.
As to your question, a base R approach uses ave
transform(df, experience = ave(quarterlyearn, sampleid, FUN = function(x) cumsum(x > 0)))
Or using dplyr::group_by
library(dplyr)
df %>% group_by(sampleid) %>% mutate(experience = cumsum(quarterlyearn > 0))
Or using data.table
syntax
library(data.table)
setDT(df)
df[, experience := cumsum(quarterlyearn > 0), by = sampleid]
All give the same result
# sampleid quarter quarterlyearn grade experience
#1 1214 1 161 10 1
#2 1214 2 523 9 2
#3 1214 3 0 8 2
#4 1214 4 919 9 3
#5 3441 1 42 12 1
#6 3441 2 0 4 1
#7 3441 3 14 7 2
#8 3441 4 0 12 2
Sample data
df <- data.frame(
sampleid = c(1214, 1214, 1214, 1214, 3441, 3441, 3441, 3441),
quarter = c(1:4, 1:4),
quarterlyearn = c(161, 523, 0, 919, 42, 0, 14, 0),
grade = c(10, 9, 8, 9, 12, 4, 7, 12))