arezaie arezaie - 2 years ago 42
R Question

R:calculating mean for every n values from a vector

So lets say I have a vector

a <- rnorm(6000)

I want to calculate the mean of the 1st value to the 60th, then again calculate the mean for the 61st value to the 120th and so fourth. So basically I want to calculate the mean for every 60th values giving me 100 means from that vector. I know I can do a for loop but I'd like to know if there is a better way to do this?

Answer Source

I would use

colMeans(matrix(a, 60))

Or more efficient without converting to matrix:

.colMeans(a, 60, 100)

Other solutions with split and lapply, or a solution with tapply will not be discussed.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download