[R] calculate multiple means of one vector

Martin Batholdy batholdy at googlemail.com
Mon Oct 10 16:56:28 CEST 2011


Dear R-Users,


I have the following two vectors:

data   <-   rnorm(40, 0, 2)

positions   <-   c(3, 4, 5,     8, 9, 10,     20, 21, 22,     30, 31, 32)
 

now I would like to calculate the mean of every chunk of data-points (of the data-vector) as defined by the positions-vector.


So I would like to get a vector with the mean of element 3 to 5 of the data-vector, 8 to 10, 20 to 22 and so on.


The gaps between the chunks are arbitrary. There is no pattern (meaning the gap from 5 to 8, 10 to 20, 22 to 30 etc.)
But the chunks are always of length n (in this case 3).


Is there a convenient way to do this without using a for-loop?


thanks!


More information about the R-help mailing list