Hi:

The plyr solution is as follows, where your 'matrix' is a data frame m whose
first column is a factor:

> m
     V1 V2 V3 V4 V5 V6 V7
1   jim  1  0  0  0  0  0
2   jim  0  1  0  0  0  0
3   jim  0  0  1  0  0  0
4   bob  1  0  0  0  0  0
5   bob  0  0  1  0  0  0
6 harry  0  0  1  0  0  0
7 harry  0  0  0  1  0  0
8 harry  0  0  0  0  1  0
9 harry  0  0  0  0  0  1
> str(m)
'data.frame':   9 obs. of  7 variables:
 $ V1: Factor w/ 3 levels "bob","harry",..: 3 3 3 1 1 2 2 2 2
 $ V2: int  1 0 0 1 0 0 0 0 0
<V3 through V7 are also numeric>

library(plyr)
ddply(m, "V1", numcolwise(sum))
     V1 V2 V3 V4 V5 V6 V7
1   bob  1  0  1  0  0  0
2 harry  0  0  1  1  1  1
3   jim  1  1  1  0  0  0

ddply() takes a data frame as input and outputs a data frame. "V1" specifies
the (categorical) variable over which reductions are desired, and
numcolwise(fun)
applies the function supplied as its argument to all numeric columns.

HTH,
Dennis

On Tue, Mar 23, 2010 at 2:15 PM, Sarah Berke <skbe...@gmail.com> wrote:

> Does anyone know if there is an R function that will take a matrix like
> this
>
> jim     1  0  0  0  0  0
> jim     0  1  0  0  0  0
> jim     0  0  1  0  0  0
> bob    1  0  0  0  0  0
> bob    0  0  1  0  0  0
> harry  0  0  1  0  0  0
> harry  0  0  0  1  0  0
> harry  0  0  0  0  1  0
> harry  0  0  0  0  0  1
>
> and make it like this? (that is, add together rows that have the same
> name?)
>
> jim    1 1 1 0 0 0
> bob   1 0 1 0 0 0
> harry 0 0 1 1 1 1
>
>
> here's the code I started with, if it helps
>
> library (dummies)
> a <- c(1,1,1,2,2,3,3,3,3)
> b<- c("A","B","C","A","C","C","D","E","F")
> name<- c("jim", "jim", "jim", "bob", "bob", "harry", "harry", "harry",
> "harry")
> MyMat <- cbind (a, b)
> rownames (MyMat) <- name
> dum.mat.temp <- dummy ("b", MyMat)
>       #dum.mat.temp <-cbind (name, dum.mat.temp) # if you want names
> as a column
> dum.mat.temp
>
> Many thanks in advance!
> --Sarah
>
> ______________________________________________
> 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.
>

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

Reply via email to