简体   繁体   中英

Sum up values for one column to a certain row in R

first of all I am sorry for the bad description, but I really don't know how to explain it better, though 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 the column the sum of all elements of the column to 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 output.

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)
})

The above is something I came up with, but it doesn't work because I don't know how to handle the variable scope.

Any ideas?

this should do you.

apply(mat, 2, cumsum)

And, it should be general for a matrix with any number of columns

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM