Sum columns by group (row names) in a matrix
Here's a vectorized base solution
rowsum(df, row.names(x))
# Mon Tue Wed Thurs
# Cake 2 1 1 2
# Pie 0 0 3 3
Or data.table
version using keep.rownames = TRUE
in order to convert your row names to a column
library(data.table)
as.data.table(x, keep.rownames = TRUE)[, lapply(.SD, sum), by = rn]
# rn Mon Tue Wed Thurs
# 1: Cake 2 1 1 2
# 2: Pie 0 0 3 3
You can try this
df <- read.table(head=TRUE, text="
Name Mon Tue Wed Thurs
Cake 1 0 1 1
Pie 0 0 1 1
Cake 1 1 0 1
Pie 0 0 1 1
Pie 0 0 1 1")
aggregate(. ~ Name, data=df, FUN=sum)
## Name Mon Tue Wed Thurs
## 1 Cake 2 1 1 2
## 2 Pie 0 0 3 3
also with dplyr
library(dplyr)
group_by(df, Name) %>%
summarise(Mon = sum(Mon), Tue = sum(Tue), Wed = sum(Wed), Thurs = sum(Thurs))
or better
group_by(df, Name) %>%
summarise_each(funs(sum))