I am using rollapply
(from the zoo
package) in R to get rolling mean values for a series of rows in a data frame.
For each row, where the focal row is x
I am trying to get a number of means. I can do this with a loop but it's slow, and I try to avoid loops.
The aim is to get rolling means for 4 different specifications:
- mean of row
x
,x-1
, andx+1
: "Rat3" - mean of row
x
through rowx+7
: "RatE" - mean of row
x+8
through rowx+15
: "RatL" - mean of row
x
through rowx+15
: "RatJ"
Using loops I can get all of these, but its slow:
tempDF = data.frame(sample(c("A","B"), replace = T, size = 100),rnorm(100,10,2))
colnames(tempDF) = c("Cohort","Rat")
for(i in 1:length(tempDF$Cohort)){
tempDF$Rat3[i] = (mean(tempDF$Rat[(i-1):(i+1 )], na.rm = FALSE))
tempDF$RatE[i] = (mean(tempDF$Rat[(i+0):(i+7 )], na.rm = FALSE))
tempDF$RatL[i] = (mean(tempDF$Rat[(i+8):(i+15)], na.rm = FALSE))
tempDF$RatJ[i] = (mean(tempDF$Rat[(i+0):(i+15)], na.rm = FALSE))
}
I can get the Rat3 using the rollapply
function:
tempDF$Rat3 = c(0,rollapply(tempDF$Rat, 3, FUN = mean, by = 1),0)
But I'm stuck in how to modify this to make it not centre around the value $x$, instead using $x$ (or $x+8$) as a starting point for the rolling average. How can I set the rollapply
function to manipulate the way it "moves" the rolling average window?
Here's an inelegant solution:
tempDF$RatE = c(0,0,0,0,rollapply(tempDF$Rat, 8, FUN = mean, by = 1),0,0,0)
tempDF$RatE = c(tempDF$RatE[5:(length(tempDF$RatE)-3)],rep("0",times=7))