user2813606
user2813606

Reputation: 911

Calculation within function not iterating correctly (R)

I am trying to write a function that calculates my salary increase every year if I assume the same percent increase each year.

I have tried some of the following code already, but it just outputs the first iteration of the calculation several times.

Here is my function:

salary_func=function(a,b){
  for(i in 1:a){
    c=b+(b*0.035)
    print(c)
  }
}

salary_func(5,100000)

The first argument should be the number of years I'd like to "forecast" out and the second argument should be the starting salary. So, I'd like to see output that reads:

[1] 103500
[1] 107122.5

and so on until the a-th argument.

But it just reads:

[1] 103500
[1] 103500

What little piece am I missing?

Upvotes: 1

Views: 36

Answers (2)

John Coleman
John Coleman

Reputation: 51998

You need to either eliminate c altogether (just use b) or initialize c, and update c relative to its previous value, rather than the original value of b. The following works:

salary_func=function(a,b){
  c = b
  for(i in 1:a){
    c=c+(c*0.035)
    print(c)
  }
}

For example:

> salary_func(5,100000)
[1] 103500
[1] 107122.5
[1] 110871.8
[1] 114752.3
[1] 118768.6

Having said that, not that a function which prints rather than returns a value is not very useful.

Upvotes: 2

Rui Barradas
Rui Barradas

Reputation: 76412

The return value of the computation must be assigned back to b, in order for it to change. Otherwise the for loop computes the same value a times.

salary_func <- function(a, b){
  for(i in seq_len(a)){
    b <- b + (b*0.035)
    print(b)
  }
}

salary_func(5, 100000)
#[1] 103500
#[1] 107122.5
#[1] 110871.8
#[1] 114752.3
#[1] 118768.6

Another solution is to take advantage of R's vectorized operations and of the fact that the function computes a compound growth.

Version 2 doesn't print the values. it returns them.

salary_func2 <- function(a, b){
    b*(1 + 0.035)^seq_len(a)
}

salary_func2(5, 100000)
#[1] 103500.0 107122.5 110871.8 114752.3 118768.6

Upvotes: 3

Related Questions