Instead of rowMeans(m[,groups == uGroups[gg], drop=FALSE]), I used apply(m[,groups == uGroups[gg], drop=FALSE], 1, mean), which really slow down the processing. I modified your codes slightly so that I can use sd, median, and mad also. Better and efficient approach ?> Date: Sun, 13 Jul 2008 18:21:24 -0700> From: [EMAIL PROTECTED]> To: [EMAIL PROTECTED]> Subject: Re: [R] Computing row means for sets of 2 columns> CC: [EMAIL PROTECTED]> > 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 <[EMAIL PROTECTED]> wrote:> >> > Is there a better or more efficent approach than this without the use of t() ?> >> >> (m <- matrix(1:40, n! col=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@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.> > _________________________________________________________________ [[elided Hotmail spam]]
[[alternative HTML version deleted]] ______________________________________________ R-help@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.