[R] get mean of several rows
Richard A. O'Keefe
ok at cs.otago.ac.nz
Fri Dec 5 04:27:48 CET 2003
"Jan Wantia" <wantia at ifi.unizh.ch> asked:
I have a 2-dimensional array, and I know how to split it into its rows
and how to get the mean for every row using 'sapply'.
But what I want is to calculate the mean over the first n rows, and then
the second n rows, etc., so that I get a vector like:
v == mean1(row 1:5), mean2(row6:10),...
(trivial, you might say.
There are lots of ways to do it.
Let Arr be a p=nrow(Arr) by q=ncol(Arr) array.
Let p %% n = 0, for simplicity.
Let 1 <= k <= p %/% n.
Then the rows which should contribute to the kth mean are
(k-1)*n+1 .. k*n.
mean(Arr[((k-1)*n+1):(k*n)])
will therefore give you the kth mean.
So
sapply(1:(nrow(Arr)%/%n), function (k) mean(Arr[((k-1)*n+1):(k*n),]))
should do the trick. I've tested it on a small example where I knew the
answers, and it worked. This assumes that I've understood the question...
I'm a bit annoyed, because I thought of several really cute ways to do
this, one involving cumsum(t(Arr)) and diff(), but this is so direct that
the others might only be confusing.
More information about the R-help
mailing list