Re: [R] Computing row means for sets of 2 columns

From: Henrik Bengtsson <hb_at_stat.berkeley.edu>
Date: Sun, 13 Jul 2008 18:21:24 -0700

m <- matrix(1:40, ncol=4);
groups <- rep(1:2, each=2);
uGroups <- unique(groups);
mMeans <- matrix(NA, nrow=nrow(m), ncol=length(uGroups)); for (gg in seq(along=uGroups)) {
  mMeans[,gg] <- rowMeans(m[,groups == uGroups[gg], drop=FALSE]); }

(Preallocation of result matrix is more memory efficient than using cbind() or similar!)

/Henrik

On Sun, Jul 13, 2008 at 6:03 PM, Daren Tan <daren76_at_hotmail.com> wrote:
>
> Is there a better or more efficent approach than this without the use of t() ?
>
>> (m <- matrix(1:40, ncol=4)) [,1] [,2] [,3] [,4] [1,] 1 11 21 31 [2,] 2 12 22 32 [3,] 3 13 23 33 [4,] 4 14 24 34 [5,] 5 15 25 35 [6,] 6 16 26 36 [7,] 7 17 27 37 [8,] 8 18 28 38 [9,] 9 19 29 39[10,] 10 20 30 40
>> (groups <- rep(1:2, each=2))[1] 1 1 2 2
>> (m.mean <- t(aggregate(t(m), by=list(groups), mean))) [,1] [,2]Group.1 1 2V1 6 26V2 7 27V3 8 28V4 9 29V5 10 30V6 11 31V7 12 32V8 13 33V9 14 34V10 15 35
> _________________________________________________________________
> Easily edit your photos like a pro with Photo Gallery.
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help_at_r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Mon 14 Jul 2008 - 01:26:35 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Mon 14 Jul 2008 - 06:31:44 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive