2

I understand what rowsum() does, but I'm trying to get it to work for myself. I've used the example provided in R which is structured as such:

x <- matrix(runif(100), ncol = 5)
group <- sample(1:8, 20, TRUE)
xsum <- rowsum(x, group)

What is the matrix of values that is produced by xsum and how are the values obtained. What I thought was happening was that the values obtained from group were going to be used to state how many entries from the matrix to use in a rowsum. For example, say that group = (2,4,3,1,5). What I thought this would mean is that the first two entries going by row would be selected as the first entry to xsum. It appears as though this is not what is happening.

D.C. the III
  • 340
  • 3
  • 14

1 Answers1

3

rowsum adds all rows that have the same group value. Let us take a simpler example.

m <- cbind(1:4, 5:8)
m
##      [,1] [,2]
## [1,]    1    5
## [2,]    2    6
## [3,]    3    7
## [4,]    4    8
group <- c(1, 1, 2, 2)
rowsum(m, group)
##   [,1] [,2]
## 1    3   11
## 2    7   15

Since the first two rows correspond to group 1 and the last 2 rows to group 2 it sums the first two rows giving the first row of the output and it sums the last 2 rows giving the second row of the output.

rbind(`1` = m[1, ] + m[2, ], `2` = m[3, ] + m[4, ])
##   [,1] [,2]
## 1    3   11
## 2    7   15

That is the 3 is formed by adding the 1 from row 1 of m and the 2 of row 2 of m. The 11 is formed by adding 5 from row 1 of m and 6 from row 2 of m.

7 and 15 are formed similarly.

G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
  • Took me some more playing around after using your example to get an understanding, but I do get it now. Thank you for your help. – D.C. the III Jan 17 '19 at 00:30