Here is a simple approach using ave()
:
df$sum.spent <- ave(df$spent, df$id, df$date2, FUN = max)
df
# id date spent date2 sum.spent
# 1 1 11-11-07 10 2007-11-11 20
# 2 1 11-11-07 20 2007-11-11 20
# 3 1 23-11-07 30 2007-11-23 30
# 4 1 12-12-08 40 2008-12-12 40
# 5 1 17-12-08 50 2008-12-17 50
# 6 3 11-11-07 60 2007-11-11 60
# 7 3 23-11-07 70 2007-11-23 80
# 8 3 23-11-07 80 2007-11-23 80
# 9 3 16-01-08 90 2008-01-16 90
It's also simple using data.table()
:
library(data.table)
# data.table 1.8.2 For help type: help("data.table")
dfDT <- data.table(df, key="id,date2")
dfDT[, sum.spent:=max(spent), by=key(dfDT)]
# id date spent date2 sum.spent
# 1: 1 11-11-07 10 2007-11-11 20
# 2: 1 11-11-07 20 2007-11-11 20
# 3: 1 23-11-07 30 2007-11-23 30
# 4: 1 12-12-08 40 2008-12-12 40
# 5: 1 17-12-08 50 2008-12-17 50
# 6: 3 11-11-07 60 2007-11-11 60
# 7: 3 23-11-07 70 2007-11-23 80
# 8: 3 23-11-07 80 2007-11-23 80
# 9: 3 16-01-08 90 2008-01-16 90