Skip to content

calculate multiple means of one vector

2 messages · Martin Batholdy, Dennis Murphy

#
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!
#
Hi:

Here's one approach:

dat   <-   rnorm(40, 0, 2)
positions   <-  matrix(c(3, 4, 5,  8, 9, 10, 20, 21, 22, 30, 31, 32),
                        ncol = 3, byrow = TRUE)
# Subdata
t(apply(positions, 1, function(x) dat[x]))
          [,1]      [,2]       [,3]
[1,] 0.5679765  1.429396  2.9050931
[2,] 4.0878845 -2.569012  2.1209280
[3,] 4.0295221 -2.659358 -1.3566887
[4,] 1.3109707 -1.745255 -0.9462857
# means of subdata
[1]  1.63415529  1.21326693  0.00449164 -0.46019018
# or
colMeans(apply(positions, 1, function(x) dat[x]))

HTH,
Dennis

On Mon, Oct 10, 2011 at 7:56 AM, Martin Batholdy
<batholdy at googlemail.com> wrote: