Sum the values ​​for one column in a specific row in R

First of all, I regret the poor description, but I really don’t know how to explain it better, although what I want to do is really simple.

Example: I have a matrix

      [,1]
 [1,]    0
 [2,]    1
 [3,]    1
 [4,]    0
 [5,]    1
 [6,]    1
 [7,]    0
 [8,]    0
 [9,]    1
[10,]    0

and I want to calculate for each row of a column the sum of all the column elements of that row.

      [,1]
 [1,]    0
 [2,]    1
 [3,]    2
 [4,]    2
 [5,]    3
 [6,]    4
 [7,]    4
 [8,]    4
 [9,]    5
[10,]    5

shoule be my way out.

mat = matrix(c(0,1,1,0,1,1,0,0,1,0), ncol=1)
summed = 0
sumup = apply(mat, 1, function(x){
    summed = summed + x
    return(summed)
})

Above was what I came across, but it does not work, because I do not know how to handle the scope of variables.

Any ideas?

+3
source share
1 answer

that should do you.

apply(mat, 2, cumsum)

And it should be common to a matrix with any number of columns

+6
source

Source: https://habr.com/ru/post/1754651/


All Articles