lokheart lokheart - 1 year ago 134
R Question

calculating cumulative sum for each row in R

I am trying to calculate the cumulative sum for each row in R 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? Thanks.

Answer Source

You want cumsum()

df <- within(df, acc_sum <- cumsum(count))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download