Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between rowsum and rowSums in R? [closed]

Tags:

r

I note that R has both of these functions: rowsum and rowSums.

However, R only has colSums, but not colsum.

Then, what is the difference between rowsum and rowSums?


1 Answers

Then, what is the difference between rowsum and rowSums?

From help("rowsum")

Compute column sums across rows of a numeric matrix-like object for each level of a grouping variable.

with my highlights. And here is help("rowSums")

Form row [...] sums and means for numeric arrays (or data frames).

So the latter gives a vector which length is the number of rows and the former gives you a [number of group] x [number of rows] output. Here are two examples

n           <- 5L
n_groups    <- 3L
n_per_group <- 4L
n_rows      <- n_groups * n_per_group

# group variable
grp <- gl(n_groups, n_per_group, labels = letters[1:n_groups])

# data matrix
set.seed(67620866)
x <- matrix(signif(runif(n_rows * n), 2), n_rows)

# sum over groups for each column
rowsum(x, grp)
#R     [,1]  [,2]  [,3] [,4] [,5]
#R a 1.9200 1.120 2.209 1.86 1.98
#R b 2.2443 1.730 1.800 2.43 1.86
#R c 2.9900 1.742 2.270 2.58 2.78
sum(x[grp == "a", 1]) # first entry
#R [1] 1.92

# sum over rows
rowSums(x)
#R  [1] 1.7190 2.8400 1.9200 2.6100 2.4300 2.7800 2.4000 2.4543 2.6800
#R [10] 3.9200 3.7440 2.0180
sum(x[1, ]) # first entry
#R [1] 1.719
like image 107
Benjamin Christoffersen Avatar answered Sep 04 '25 23:09

Benjamin Christoffersen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!