Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
375 views
in Technique[技术] by (71.8m points)

r - Sum columns by group (row names) in a matrix

Let's say I have a matrix called x.

x <- structure(c(1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1), 
.Dim = c(5L, 4L), .Dimnames = list(c("Cake", "Pie", "Cake", "Pie", "Pie"),
c("Mon", "Tue", "Wed", "Thurs"))) 

x
     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

I want to sum each column grouped by row names:

     Mon   Tue   Wed   Thurs
Cake   2     1     1      2
Pie    0     0     3      3

I've tried using addmargins(x), but that just gives me the sum of each column and row. Any suggestions? I searched other questions, but couldn't figure this out.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...