0

I'm quite new to coding, so I don't know what the limits are for what I can do in R, and I haven't been able to find an answer for this particular kind of problem yet, although it probably has quite a simple solution.

For equation 2, A.1 is the starting value, but in each subsequent equation I need to use the previous answer (i.e. for A.3 I need A.2, for A.4 I need A.3, etc.).

  1. A.1 <- start.x*(1-rate[1])+start.x*rate[1]

  2. A.[2:n] <- A.[n-1]*(1-rate[2:n])+x*rate[2:n]

How do I set A.1 as the initial value, and is there a better way of writing equation 2 than to copy and paste the equation 58 times?

I've included the variables I have below:

A.1<- -13.2 # which is the same as start.x 
x<- -10.18947 # x[2:n]
n<- 58
Age<-c(23:80)

rate <- function(Age){
  Turnover<-(1/(1.0355*Age-3.9585))
  return(Turnover)
}

I need to find the age at which A can be rounded to -11.3. I expect to see it from ages 56 to 60.

Tricia
  • 3
  • 3
  • Can you give 2 or 3 examples of input and expected output? – Rui Barradas Jul 31 '20 at 17:46
  • 1
    Please include data for `start.x` and `rate`. – Parfait Jul 31 '20 at 17:49
  • 2
    Just a note: `start.x*(1-rate[1])+start.x*rate[1]` can be simplified by `start.x-start.x*rate[1]+start.x*rate[1] = start.x` – Marco Sandri Jul 31 '20 at 18:06
  • It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Jul 31 '20 at 21:06

1 Answers1

0

Using the new information, try this:

x<- -10.18947
n<- 58
Age <- 23:80
rate <- (1 / (1.0355 * Age - 3.9585))
A <- vector("numeric", 58)
A[1] <- -13.2
for (i in 2:n) {
    A[i] <- A[i-1] * (1 - rate[i]) + x * rate[i]
}
Age[which.min(abs(A + 11.3))]
# [1] 58
plot(Age, A, type="l")
abline(h=-11.3, v=58, lty=3)

So the closest age to -11.3 is 58 years. Plot

dcarlson
  • 10,936
  • 2
  • 15
  • 18
  • Thanks, yes, if x is the same as start.x, all the equations should equal to start.x. I've added new data to clarify my problem. – Tricia Aug 03 '20 at 19:16