Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Increment a variable by 5% every week in R

I have the following data:

date <- seq.Date(from = as.Date("2022-01-01"), to = as.Date("2022-07-01"), by = "day")
value <- rep(500, length(date))
mydf <- cbind.data.frame(date, deliveries)

I want to increment my value variable by 5% EACH WEEK, i.e., mydf$value[1:7] remains unchanged, mydf$value[8:14] become 500*(1.05) = 525, mydf$value[15:21] become 525*(1.05) = 551.25, and so on.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

the folowing will work, also when your series of dates is not continuous.

It will calculate the difference from each date with the first date, in weeks. Rounds down and then use that num,ber as the power of 1.05.

mydf$newValue <- value * 1.05^(as.numeric(floor(difftime(mydf$date, mydf$date[1], units = "weeks"))))

          date value  newValue
1   2022-01-01   500  500.0000
2   2022-01-02   500  500.0000
3   2022-01-03   500  500.0000
4   2022-01-04   500  500.0000
5   2022-01-05   500  500.0000
6   2022-01-06   500  500.0000
7   2022-01-07   500  500.0000
8   2022-01-08   500  525.0000
9   2022-01-09   500  525.0000
10  2022-01-10   500  525.0000
11  2022-01-11   500  525.0000
12  2022-01-12   500  525.0000
13  2022-01-13   500  525.0000
14  2022-01-14   500  525.0000
15  2022-01-15   500  551.2500
16  2022-01-16   500  551.2500
17  2022-01-17   500  551.2500
18  2022-01-18   500  551.2500
19  2022-01-19   500  551.2500
20  2022-01-20   500  551.2500
21  2022-01-21   500  551.2500
22  2022-01-22   500  578.8125
23  2022-01-23   500  578.8125
24  2022-01-24   500  578.8125
25  2022-01-25   500  578.8125
26  2022-01-26   500  578.8125
27  2022-01-27   500  578.8125
28  2022-01-28   500  578.8125
29  2022-01-29   500  607.7531
...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading