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

Time:01-02

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.

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!

CodePudding user response:

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
  •  Tags:  
  • r
  • Related