Использование aggregate
. Переменная год-месяц ym
, которую мы можем создать с помощью substr
от первого до седьмого символа столбца даты.
m <- with(dat, aggregate(list(return=return),
by=list(ym=substr(date, 1, 7), id=id), sum))
m
# ym id return
# 1 2000-07 1 2.6
# 2 2000-07 2 3.1
Или tapply
.
m <- with(dat, tapply(return, list(ym=substr(date, 1, 7), id=id), sum))
m
# id
# ym 1 2
# 2000-07 2.6 3.1
Данные
dat <- structure(list(date = c("2000-07-06", "2000-07-07", "2000-07-09",
"2000-07-10", "2000-07-15", "2000-07-16", "2000-07-20", "2000-07-21",
"2000-07-06", "2000-07-07", "2000-07-15", "2000-07-16", "2000-07-17",
"2000-07-18"), event = c(2L, 1L, 0L, 0L, 2L, 1L, 0L, 1L, 1L,
2L, 0L, 0L, 2L, 1L), id = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L,
2L, 2L, 2L, 2L, 2L), return = c(0.1, 0.2, 0.6, 0.4, 0.7, 0.3,
0.1, 0.2, 0.3, 0.4, 0.6, 0.8, 0.9, 0.1)), row.names = c(NA, -14L
), class = "data.frame")