dt = data.table(structure(list(CaseID = c(1, 1, 1, 2, 2, 3, 4, 5), Won = structure(c(3L,
3L, 3L, 2L, 2L, 3L, 2L, 1L), .Label = c("15", "no", "yes"), class = "factor"),
OwnerID = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L), .Label = c("A",
"B"), class = "factor"), Time_period = c(1L, 3L, 5L, 4L,
6L, 2L, 3L, 2L), Finished = structure(c(1L, 1L, 2L, 1L, 2L,
2L, 2L, 1L), .Label = c("no", "yes"), class = "factor")), .Names = c("CaseID",
"Won", "OwnerID", "Time_period", "Finished"), row.names = c(NA,
-8L), class = c("data.table", "data.frame")))
setkey(dt, OwnerID, Time_period)
dt[, ratio := cumsum(Finished == "yes" & Won == "yes") /
cumsum(Finished == "yes"),
by = list(OwnerID)]
dt[, avgWon := c(NaN, ratio[-.N]), by = OwnerID]
dt[, avgWon := avgWon[1], by = key(dt)]
dt[order(OwnerID, CaseID)]