# Data
dat = data.frame(
id = c(1, 1, 1, 2, 2, 2),
date = c("2020-01-01", "2020-03-01", "2020-04-30", "2020-02-02", "2020-02-02", "2020-04-05"),
num = c(10, 20, 30, 10, 20, 30),
interactions = c(2, 6, 7, 3, 6, 8)
)
dat
## id date num interactions
## 1 1 2020-01-01 10 2
## 2 1 2020-03-01 20 6
## 3 1 2020-04-30 30 7
## 4 2 2020-02-02 10 3
## 5 2 2020-02-02 20 6
## 6 2 2020-04-05 30 8
###########################
# Original observations
grid = dat[, c("id", "date", "num")]
# Aggregate
dat = aggregate(dat["interactions"], dat[c("id", "date")], sum)
# Order
dat = dat[order(dat$id, dat$date), ]
# Split by 'id'
dat = split(dat, dat$id)
# Cumulative sum excluding self
f = function(x) {x$interactions = cumsum(x$interactions) - x$interactions; x}
dat = lapply(dat, f)
# Combine
dat = do.call(rbind, dat)
# Join with original observations
dat = merge(grid, dat, by = c("id", "date"), all.x = TRUE)
# Final result
dat
## id date num interactions
## 1 1 2020-01-01 10 0
## 2 1 2020-03-01 20 2
## 3 1 2020-04-30 30 8
## 4 2 2020-02-02 10 0
## 5 2 2020-02-02 20 0
## 6 2 2020-04-05 30 9