Matt Jordan
Matt Jordan

Reputation: 587

Create a 7-day rolling mean by Group

I want to create a 7-day rolling mean for a daily physical training load over a year calculated for each athlete in a training group.

The data set is called 'daily.load'. The vectors are: 'Date', 'Name', 'Total.Load'

The ideal end result would be a rolling 7-day mean for 'Total.Load' as a fourth vector called 'Rolling.Average' in the 'daily.load' data set.

I am attempting to do this with rollmean but I'm getting stuck when it comes to getting the function to generate the rolling mean by athlete.

Any help would be greatly appreciate.

Matt

Upvotes: 1

Views: 1695

Answers (2)

Matt Jordan
Matt Jordan

Reputation: 587

Thank you Shadow. The exact code that worked was:

setDT(daily.load)

daily.load[, Rolling.Average := rollmean(Total.Load, 7, fill = NA, align="right"), by = Name]

The align="right" vs. align="centre" is a great option. Also remember for R neophytes to distinguish whether or not you have a data table or a data frame.

Upvotes: 0

shadow
shadow

Reputation: 22293

There is a by argument in data.table, so calculating the rolling mean by athlete should not be a problem. Below is a reproducible example, where I calculated the rolling average with rollmean. Also note that RcppRoll::roll_mean is probably way faster than zoo::rollmean.

# load packages
require(data.table)
require(zoo)
# create data
Ndays <- 100
Nnames <- 5
daily.load <- data.table(Date = rep(Sys.Date() - seq.int(Ndays, 1), times = Nnames), 
                         Name = rep(LETTERS[seq(Nnames)], each=Ndays), 
                         Total.Load = rnorm(Ndays*Nnames, 100, 5))
setkey(daily.load, "Name", "Date")
# calculate rolling average by Name
daily.load[, Rolling.Average := rollmean(Total.Load, 7, fill = NA), by = Name]

Upvotes: 2

Related Questions