tags:

views:

85

answers:

1

Hi all,

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?

+6  A: 

this should do you.

apply(mat, 2, cumsum)

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

JoFrhwld
Never mind, way better answer. This is what I get for not knowing R. :)
allie
Thanks a lot. That worked.
Sebastian
I big step in learning R has been letting go of my Matlab desires to do everything as a matrix. If you can use a vector instead, this becomes really easy with Jo's wise use of `cumsum`.`> mat <- mat[,1]``> mat`` [1] 0 1 1 0 1 1 0 0 1 0``> sumup <- cumsum(mat)``> sumup`` [1] 0 1 2 2 3 4 4 4 5 5`
richardh