Skip to content
Back to formatted view

Raw Message

Message-ID: <13EA8D71-DFD8-41D8-8CF4-09B158DB48AD@googlemail.com>
Date: 2011-10-10T14:56:28Z
From: Martin Batholdy
Subject: calculate multiple means of one vector

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!