[R] separate row averages for different parts of an array

Marc Schwartz (via MN) mschwartz at mn.rr.com
Wed Aug 16 20:35:18 CEST 2006


On Wed, 2006-08-16 at 11:36 -0600, Spencer Jones wrote:
> I have an array with 44800 columns and 24 rows I would like to compute the
> row average for the array 100 columns at a time, so I would like to end up
> with an array of 24 rows x 448 columns. I have tried using apply(dataset, 1,
> function(x) mean(x[])), but I am not sure how to get it to take the average
> 100 columns at a time. Any ideas would be  welcomed.
> 
> thanks,
> 
> Spencer

Something along the lines of the following, presuming that 'mat' is your
24 * 44800 matrix:

  sapply(seq(1, 44800, 100), function(x) rowMeans(mat[, x:(x + 99)]))


The first argument in sapply() creates a sequence from 1:44800 by
increments of 100. 

sapply() then passes each value in the sequence as the starting index
value 'x' to use to subset 'mat' in 100 column sets and gets the
rowMeans() for each sub-matrix.

The returned object will be a 24 * 448 matrix.

HTH,

Marc Schwartz



More information about the R-help mailing list