Sebastian
Sebastian

Reputation: 633

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?

Upvotes: 3

Views: 3561

Answers (1)

JoFrhwld
JoFrhwld

Reputation: 9057

this should do you.

apply(mat, 2, cumsum)

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

Upvotes: 7

Related Questions