Using the input shown reproducibly in the Note at the end, use rollapplyr
specifying offsets -1, -2, -3 and use the argument partial=TRUE
to let it use fewer than the specified offsets if only fewer are available. The first element cannot be calculated since there are no prior elements so for that specify that the first element be filled in using the fill
argument.
library(zoo)
DF2 <- transform(DF, roll =
rollapplyr(Original, list(-(1:3)), mean, partial = TRUE, fill = Original[1]))
with(DF2, identical(Desired, roll)) # check that result matches Desired
## [1] TRUE
Note
Lines <- "
Days Original Desired
1 2 2
2 4 2
3 1 3
4 3 7/3
5 5 8/3
6 6 9/3
7 4 14/3
8 9 15/3"
DF <- read.table(text = Lines, header = TRUE)
DF <- transform(DF, Desired = sapply(Desired, function(x) eval(parse(text = x))))
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…