sym246
sym246

Reputation: 1866

Rolling year to date average in R

How would I compute the (financial) year to date average of a data set in R?

My data is of the form:

library(zoo)
DF=data.frame(Day=seq(as.POSIXct("2017-03-01"), as.POSIXct("2017-06-07"),"day"),Value=rnorm(98,1,2))
DF$`5day_rolling`=rollmean(DF$Value,5,fill=NA,align="left")

DF$Financial_yr=as.numeric(format(DF$Day, "%Y")) + (format(DF$Day, "%m") >= "04")

Where I have thus far calculated the 5 day rolling mean. I have added a financial year column, which is to be used for the year to date average. So, what i'd like, is an additional column which starts by being equal to the first value of the first day of FY1, the second value being an average of the first 2 days, third being average of three etc..

Upvotes: 1

Views: 655

Answers (1)

G. Grothendieck
G. Grothendieck

Reputation: 269481

Use ave to group by financial year and then use cumsum(x)/seq_along(x) to calculate the year-to-date average. No packages are used.

cumavg <- function(x) cumsum(x) / seq_along(x)
transform(DF, avg_ytd = ave(Value, Financial_yr, FUN = cumavg))

Upvotes: 4

Related Questions