On Jul 11, 2011, at 9:23 AM, Joshua Wiley wrote:
Hi,
Take a look at package "zoo", perhaps something like:
require(zoo)
x <- rnorm(10000) # hypothetical data
m <- rollapply(zoo(x), width = 100, FUN = mean, by = 100)
Definitely a better answer, but if all your rolling averages were of
the form you suggested, then rollapply might be overkill, since tapply
could easily do it:
tapply(x, rep(1:100, each=100), mean)
If you were always using non-overlapping blocks, then something like
tapply(x, rep(1:( length(x)/wid ) , each= wid) , mean)
Which will throw an error if length is not an integer multiple of "wid"
Another (bit more of a hack) option would be:
## convert vector to matrix byrows with 100 columns per row
## (where 100 is the number of points you want at a time)
## use rowMeans function to get mean of each row quickly
m2 <- rowMeans(matrix(x, ncol = 100, byrow = TRUE))
?rollapply # from package zoo
?rowMeans # in base
For Joshua's colMeans(matrix(..)) approach you need to be careful "at
the end" because of recycling or at least heed warnings. I suspect
that rollapply has protections built-in to avoid spurious recycling.
> matrix(c(1,2,3), 2, byrow=TRUE)
[,1] [,2]
[1,] 1 2
[2,] 3 1
--
David.
HTH,
Josh
On Mon, Jul 11, 2011 at 2:23 AM, M. B <workstu...@googlemail.com>
wrote:
Hello,
I am running R on Linux and have a column of data 10000 points
long. I would
like to take a moving average of say 100 points at a time, so I end
up with
one column of 100 points. What is the simplest way of doing this?
I would
like to be able to adjust the width of the averaging blocks.
Thanks much!
[[alternative HTML version deleted]]
David Winsemius, MD
West Hartford, CT
______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.