[R] How to create running averages
arun
smartpink111 at yahoo.com
Wed Nov 20 16:03:06 CET 2013
Hi,
Not sure if this is what you wanted.
mydf[,1] <- mydf[,1]+ISOdatetime(1970,1,1,0,0,0)
library(zoo)
z1 <- zoo(mydf[,2],mydf[,1])
fun1 <- function(z,n,k){
unlist(lapply(split(z,((seq_along(z)-1) %/% n) +1), function(x) rollapply(c(rep(NA,k),x),width=n,mean,na.rm=TRUE)),use.names=FALSE)
}
#1-10
fun1(z1,10,9)
#1-3
fun1(z1,3,2)
#4-7
fun1(z1,7,3)
#8-10
fun1(z1,10,2)
A.K.
I have a data frame that contains daily temperature and want to
calculate running averages from the lags. How could I create the
following four averages: 1 to 10 days, 1 to 3 days and 4 to 7 days and 8 to 10 days?
Thanks
> dput(mydf)
structure(list(mydate = c(1104537600, 1104624000, 1104710400,
1104796800, 1104883200, 1104969600, 1105056000, 1105142400, 1105228800,
1105315200, 1105401600, 1105488000, 1105574400, 1105660800, 1105747200,
1105833600, 1105920000, 1106006400, 1106092800, 1106179200, 1106265600,
1106352000, 1106438400, 1106524800, 1106611200, 1106697600, 1106784000,
1106870400, 1106956800, 1107043200, 1107129600, 1107216000, 1107302400,
1107388800, 1107475200, 1107561600, 1107648000, 1107734400, 1107820800,
1107907200, 1107993600, 1108080000, 1108166400, 1108252800, 1108339200,
1108425600, 1108512000, 1108598400, 1108684800, 1108771200, 1108857600,
1108944000, 1109030400, 1109116800, 1109203200, 1109289600, 1109376000,
1109462400, 1109548800, 1109635200), temperature = c(27.2355645811212,
24.7572454841433, 25.8807360325073, 23.604983194918, 25.3806158930898,
25.4522163920789, 23.3634003395322, 21.8857290467555, 25.7885123837986,
25.2892335838452, 28.576293971409, 23.9336020581815, 27.0939456273958,
28.3913410122702, 25.909021640904, 26.2460484822251, 25.1575616245794,
22.8368740313366, 27.6642857968485, 25.1196788026597, 22.5894167843065,
30.2988617359284, 24.8434897031825, 23.4057719286007, 24.4344849657242,
26.1064563281548, 28.8237562787261, 26.2779314012608, 24.9246895989705,
25.9247118455481, 26.8168149658814, 24.5976817973611, 23.0279799404805,
23.8692145542798, 20.5706428459246, 25.2535816755043, 24.1579034687891,
26.2783929119493, 24.1524000712139, 23.6602196383023, 24.0011597837778,
21.2285591199996, 26.019106804625, 27.8057491046718, 24.3857746554726,
27.0899941525061, 29.3171144596242, 25.6280205868316, 24.5556883088479,
27.8460189886338, 27.614311224526, 26.3826496863349, 23.357578632432,
22.6042279901428, 23.3671729098119, 26.3785847646844, 24.3646932790827,
25.9119679458049, 26.5848087900931, 27.0119408766481)), .Names = c("mydate",
"temperature"), row.names = c(NA, -60L), class = "data.frame")
More information about the R-help
mailing list