[R] Aggregating the matrices

Gabor Grothendieck ggrothendieck at gmail.com
Mon Sep 6 16:01:49 CEST 2010


On Mon, Sep 6, 2010 at 9:56 AM, Sergey Goriatchev <sergeyg at gmail.com> wrote:
> Hello everyone.
>
> Say we have the following:
>
> a <- matrix(c(-75, 3, 5, 9, 2, 3, 5), nrow=1, dim=list("06092010",
> c("ES", "PT", "Z ", "CF", "GX", "ST", "EO")))
> b <- matrix(c(-5, 2, 4, 12, 5), nrow=1, dim=list("06092010", c("PT",
> "CF", "AT", "EM", "ST")))
> d <- cbind(a, b)
>
> I want to calculate sums of the columns that have similar column names
> and then output this summary
> What I want to have is an array that looks like:
>
> ES  PT Z  CF...
> -75  -2  5  11...
>
> I tried the following, but it did not work:
> aggregate(d, list(colnames(d)), sum)
>
> How can I achieve my objective?
>
> Thank you in advance.
>


Try this:

> library(plyr)
> colSums(rbind.fill(as.data.frame(a), as.data.frame(b)), na.rm = TRUE)
 ES  PT  Z   CF  GX  ST  EO  AT  EM
-75  -2   5  11   2   8   5   4  12




-- 
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com



More information about the R-help mailing list