[R] Computing row means for sets of 2 columns

Henrik Bengtsson hb at stat.berkeley.edu
Mon Jul 14 03:21:24 CEST 2008


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.
>



More information about the R-help mailing list