Skip to content

apply to row and column of matrix

3 messages · Jinsong Zhao, Bert Gunter, Eric Berger

#
Hi there,

I try to calculate the cumsum of row and column of a matrix as follows.

 > m <- matrix(1:10, ncol = 2)
 > m
 ???? [,1] [,2]
[1,]??? 1??? 6
[2,]??? 2??? 7
[3,]??? 3??? 8
[4,]??? 4??? 9
[5,]??? 5?? 10
 > apply(m, 1, cumsum)
 ???? [,1] [,2] [,3] [,4] [,5]
[1,]??? 1??? 2??? 3??? 4??? 5
[2,]??? 7??? 9?? 11?? 13?? 15
 > apply(m, 2, cumsum)
 ???? [,1] [,2]
[1,]??? 1??? 6
[2,]??? 3?? 13
[3,]??? 6?? 21
[4,]?? 10?? 30
[5,]?? 15?? 40

My question is why the dim of the return value of apply(m, 1, cumsum) is 
not 5x2, but 2x5.

Best,

Jinsong
#
from ?apply:
"If each call to FUN returns a vector of length n, and simplify is
TRUE, then apply returns an array of dimension c(n, dim(X)[MARGIN]) ."

For margin = 1 (cumsum over rows), each call to cumsum return a vector
of length 2. Hence the array returned will be of dimension c(2,
c(5,2)[1]) = c(2,5).

Cheers,
Bert
On Mon, Sep 26, 2022 at 7:43 AM Jinsong Zhao <jszhao at yeah.net> wrote:
#
Bert provided an excellent answer to your question.
FYI here is a different approach to do the calculation.
It uses data.frame rather than matrix. A data frame is a list of its columns.
Here the function supplied to sapply operates on each column of the data.frame.
V1  V2  V3  V4  V5
1   1     2    3     4    5
2    6    7    8     9   10
V1  V2  V3  V4  V5
[1,]    1     2    3     4    5
[2,]    7     9   11   13  15
On Mon, Sep 26, 2022 at 5:57 PM Bert Gunter <bgunter.4567 at gmail.com> wrote: