Examples for 'base::rowsum'


Give Column Sums of a Matrix or Data Frame, Based on a Grouping Variable

Aliases: rowsum rowsum.default rowsum.data.frame

Keywords: manip

### ** Examples

require(stats)

x <- matrix(runif(100), ncol = 5)
group <- sample(1:8, 20, TRUE)
(xsum <- rowsum(x, group))
       [,1]      [,2]      [,3]      [,4]      [,5]
1 2.3069958 2.5842574 1.9114070 1.2309019 0.6970973
3 2.5700753 1.9139760 1.5932485 2.3791303 1.8539666
4 1.5173623 0.7908481 1.1074418 2.1654941 2.1420441
5 1.2223516 1.4106666 0.3725383 0.7536322 0.8717439
6 0.6455511 1.0024951 1.6355687 1.2063507 0.5527338
7 1.7893957 1.5433833 1.7864082 1.1263631 1.7256937
8 1.6901498 1.5161488 1.1149819 0.9984796 1.2302675
## Slower versions
tapply(x, list(group[row(x)], col(x)), sum)
          1         2         3         4         5
1 2.3069958 2.5842574 1.9114070 1.2309019 0.6970973
3 2.5700753 1.9139760 1.5932485 2.3791303 1.8539666
4 1.5173623 0.7908481 1.1074418 2.1654941 2.1420441
5 1.2223516 1.4106666 0.3725383 0.7536322 0.8717439
6 0.6455511 1.0024951 1.6355687 1.2063507 0.5527338
7 1.7893957 1.5433833 1.7864082 1.1263631 1.7256937
8 1.6901498 1.5161488 1.1149819 0.9984796 1.2302675
t(sapply(split(as.data.frame(x), group), colSums))
         V1        V2        V3        V4        V5
1 2.3069958 2.5842574 1.9114070 1.2309019 0.6970973
3 2.5700753 1.9139760 1.5932485 2.3791303 1.8539666
4 1.5173623 0.7908481 1.1074418 2.1654941 2.1420441
5 1.2223516 1.4106666 0.3725383 0.7536322 0.8717439
6 0.6455511 1.0024951 1.6355687 1.2063507 0.5527338
7 1.7893957 1.5433833 1.7864082 1.1263631 1.7256937
8 1.6901498 1.5161488 1.1149819 0.9984796 1.2302675
aggregate(x, list(group), sum)[-1]
         V1        V2        V3        V4        V5
1 2.3069958 2.5842574 1.9114070 1.2309019 0.6970973
2 2.5700753 1.9139760 1.5932485 2.3791303 1.8539666
3 1.5173623 0.7908481 1.1074418 2.1654941 2.1420441
4 1.2223516 1.4106666 0.3725383 0.7536322 0.8717439
5 0.6455511 1.0024951 1.6355687 1.2063507 0.5527338
6 1.7893957 1.5433833 1.7864082 1.1263631 1.7256937
7 1.6901498 1.5161488 1.1149819 0.9984796 1.2302675

[Package base version 4.2.3 Index]