Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
227 views
in Technique[技术] by (71.8m points)

r - 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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You want cumsum()

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...