Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

dataframe - Multiply previous row value by constant R

Have a simple R question but cannot seem to find an answer:

I have a data frame like this:

assumption_val year
1.2            2015
0              2016
0              2017
0              2018
0              2019

I want to grow each value as 20% greater than compared to the previous year, to output something like this:

assumption_val year
1.2            2015
1.44           2016
1.73           2017
2.07           2018
2.49           2019

How can I reference the previous row and multiply it by 1.2 to achieve this?

Thanks!

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You are looking for cumprod:

cumprod(rep(1.2, 5))

Like its better known friend, cumsum, it accumulates past results, but it performs a multiplication rather than addition.

df <- data.frame(assumption_val=cumprod(rep(1.2, 5)), 
                 years=2015:2019)

A nice generalization of these functions is Reduce. For example, here is Reduce performing this calculation. You can replace the "*" with "+" and have cumsum.

Reduce("*", rep(1.2, 5), accumulate = T)

A nice feature of this method is that you can adjust the growth rate in each period. For instance if you wanted to start at 1.5 rather than 1.2, you would simply adjust your growth vector to c(1.5, rep(1.2, 4)) to calculate the new growth as follows:

cumprod(c(1.5, rep(1.2, 4)))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...