## R sum rows of matrix by column name

Question

This seems like it should be easy but I can't figure it out. I would like to sum all of the columns of my matrix that have the same name. So, in the example below, I would like to end up with another matrix with only three columns.

```
set.seed(4)
z<-matrix(sample(1:10,20, replace=T), nrow=4)
colnames(z)<-c("a","c","b","a","b")
z
a c b a b
[1,] 6 9 10 2 10
[2,] 1 3 1 10 6
[3,] 3 8 8 5 10
[4,] 3 10 3 5 8
```

should yield:

```
a c b
[1,] 8 9 20
[2,] 11 3 7
[3,] 8 8 18
[4,] 8 10 11
```

I tried:

```
z<-aggregate(colnames(z), data=z, sum)
```

but it did not work. I would prefer to use base R if possible.

Show source

## Answers to R sum rows of matrix by column name ( 4 )

Try this:

You can use

`rowsum`

with the column names as`group`

variable:Here is an option using

`xtabs`

Or with

`tapply`

This will also do.

Resulting in