Calculating cumulative sum for each row

I am trying to calculate the cumulative sum for each row using the following code:

df <- data.frame(count=1:10)

for (loop in (1:nrow(df)))
    {df[loop,"acc_sum"] <- sum(df[1:loop,"count"])}

But I don't like the explicit loop here, how can I modify it?


Solution 1:

You want cumsum()

df <- within(df, acc_sum <- cumsum(count))

Solution 2:

You can also try mySum = t(apply(df, 1, cumsum)).

The transpose is in there because the results come out transposed, for a reason I have not yet determined.

I'm sure there are fine solutions with plyr, such as ddply and multicore methods.