# [R] Question on matrix calculation

David L Carlson dcarlson at tamu.edu
Thu Jan 24 22:27:56 CET 2013

```Or just use aggregate()

# Redefine match_df to match your data.frame
> match_df <- data.frame(Seq = 1:5, criteria = letters[c(3, 5, 3, 3, 4)])
> aggregate(mat, list(match_df\$criteria), sum)
Group.1 V1 V2 V3
1       a  7 17 27
2       c  2  7 12
3       d  6 16 26
# If you really want a matrix:
> as.matrix(aggregate(mat, list(match_df\$criteria), sum)[,2:4])
V1 V2 V3
[1,]  8 23 38
[2,]  5 10 15
[3,]  2  7 12

----------------------------------------------
David L Carlson
Associate Professor of Anthropology
Texas A&M University
College Station, TX 77843-4352

> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-
> project.org] On Behalf Of arun
> Sent: Thursday, January 24, 2013 2:27 PM
> To: Christofer Bogaso
> Cc: R help
> Subject: Re: [R] Question on matrix calculation
>
> Hi,
>
> You could also use:
> mat <- matrix(1:15, 5)
> set.seed(5)
> match_df <- data.frame(Seq = 1:5, criteria = sample(letters[1:5], 5,
> replace = T),stringsAsFactors=F)
> library(plyr)
> res<-daply(as.data.frame(mat),.(match_df\$criteria),colSums)
> res
>
> #match_df\$criteria V1 V2 V3
>   #              a  5 10 15
>    #             b  5 15 25
>     #            d  2  7 12
>       #          e  3  8 13
>
>
> A.K.
>
>
>
> ----- Original Message -----
> From: Christofer Bogaso <bogaso.christofer at gmail.com>
> To: r-help <r-help at r-project.org>
> Cc:
> Sent: Thursday, January 24, 2013 2:39 PM
> Subject: [R] Question on matrix calculation
>
> Hello again,
>
> Ley say I have 1 matrix and 1 data frame:
>
> > mat <- matrix(1:15, 5)
> > match_df <- data.frame(Seq = 1:5, criteria = sample(letters[1:5], 5,
> replace = T))
> > mat
>      [,1] [,2] [,3]
> [1,]    1    6   11
> [2,]    2    7   12
> [3,]    3    8   13
> [4,]    4    9   14
> [5,]    5   10   15
> > match_df
>   Seq criteria
> 1   1        c
> 2   2        e
> 3   3        c
> 4   4        c
> 5   5        d
>
> Now I want to get the column-sums of 'mat' based on the unique
> elements of match_df[,'criteria']
>
> Therefore based on the 'match_df', my resulting matrix will have 3
> rows (because the unique elements here are 'c, e, & d'). And.........
>
> 1st row will be column sums for mat[c(1,3,4), ]
> 2nd row will be column sums for mat[c(2), ]
> 3rd row will be column sums for mat[c(5), ]
>
> I want to get a general framework, so that I can implement that in
> some big arbitrary matrix.
>
> Can somebody give me some pointer?
>
> Thanks and regards,
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> 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