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

R – Populate a vector via rep with an increasing exponential value

I have one vector like this:

years <- c(2021:2091)

And I want to create another vector to bind to it based off an initial value and inrease compound-like for every row based on an arbitrary decimal(such as 10%, 15%, 20%):

number = x
rep(x*(1 + .10)^n, length(years))

How do I replicate the length of years for the second vector while increasing the exponent every time. Say there is 71 rows in years, I need n to start at 1 and run through 71.

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

I have tried:

rep(x*(1 + .10)^(1:71), length(years))

But this does it 71*71 times. I just need one value for each exponent!

Hopefully this makes sense, thanks in advance!

>Solution :

Here is how you could do it with a function:

future_value = function(years, x = 1, interest = 0.1) {
  x * (1 + interest) ^ (1:length(years))
}

Example outputs:

> future_value(2021:2025)
[1] 1.10000 1.21000 1.33100 1.46410 1.61051

> future_value(2021:2025, x = 2, interest = 0.15)
[1] 2.300000 2.645000 3.041750 3.498012 4.022714
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