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

From: Daren Tan <daren76_at_hotmail.com>
Date: Mon, 14 Jul 2008 02:23:38 +0000

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: hb_at_stat.berkeley.edu> To: daren76_at_hotmail.com> Subject: Re: [R] Computing row means for sets of 2 columns> CC: r-help_at_stat.math.ethz.ch> > 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, 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_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 - 02:33:00 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 - 07:32:47 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