Это можно сделать довольно эффективно с помощью tapply
. Я несколько изменил ваши данные, дублируя игры команд, со случайными оценками и датами. Для этого требуется среднее значение двух последних игр, как указано в функции tail
.
# create some data
d <- structure(list(Div = structure(rep(1L, 33), .Label = " E0",
class = "factor"), date = structure(c(15013, 14990, 14996, 15001, 14995, 15006,
15020, 15032, 15023, 15022, 15015, 15016, 15034, 14994, 14986, 14998, 14982,
14979, 14980, 15016, 15031, 15013, 15031, 14999, 15025, 14978, 15007, 15026,
14992, 14997, 15023, 14986, 15028), class = "Date"),
value = structure(c(3L, 4L, 5L, 7L, 8L, 11L, 9L, 10L, 6L, 1L, 2L, 3L, 4L, 5L,
7L, 8L, 11L, 9L, 10L, 6L, 1L, 2L, 3L, 4L, 5L, 7L, 8L, 11L, 9L, 10L, 6L, 1L,
2L), .Label = c("Arsenal", "Aston Villa", "Blackburn", "Fulham", "Liverpool",
"Man City", "Newcastle", "QPR", "Stoke", "West Brom", "Wigan"),
class = "factor"), pts = c(0.5, 0.5, 0.5, 1, 1, 1, 1, 0, 1, 0.5, 0, 1, 1, 1, 1,
0.5, 0.5, 0, 0.5, 0.5, 0, 0, 0, 1, 0, 0, 0.5, 0, 1, 0, 0.5, 0.5, 0.5)),
.Names = c("Div", "date", "value", "pts"), row.names = c(NA, 33L),
class = "data.frame")
# sort rows by date
d2 <- d[order(d$date),]
# mean of all games
tapply(d2$pts, d2$value, mean)
# mean of last 2 games
tapply(d2$pts, d2$value, function(x) mean(tail(x, 2)))
# To tidy up the output, you could use simplify=FALSE and do.call(rbind, x):
# e.g., mean of last 2 games:
do.call(rbind, tapply(d2$pts, d2$value, function(x) mean(tail(x, 2)),
simplify=F))
[,1]
Arsenal 0.25
Aston Villa 0.25
Blackburn 0.50
Fulham 1.00
Liverpool 0.25
Man City 0.75
Newcastle 1.00
QPR 0.50
Stoke 1.00
West Brom 0.00
Wigan 0.50