0

I write a R function using if & else if in it. See the code below:

i_ti_12 <- function(x){
  if (x <= 44)
  {ti = exp(-13.2238 + 0.152568*x)}
  else if (x >= 49)
  {ti = -0.01245109 + 0.000315605*x}
  else (x > 44 & x < 49)
  {ti = (x-44)*(i_ti_12(49))/(49-44) + (49-x)*(i_ti_12(44))/(49-44)}
  return(ti)
}

I want to use this function's output, i_ti_12(49) within this function, but the above code doesn't work. The output is:

> i_ti_12(49)
Error: C stack usage  7974292 is too close to the limit

The simple solution is just replace i_ti_12(49) by -0.01245109 + 0.000315605*49, but its not a clear way to solve it and might not work in complex cases.

So I really want to know and to learn if there are clear methods to do this? I mean, like above simple example, write a conditional function using one condition's output in this function. Any help is highly appreciate.

1 Answer 1

2

Your last else is followed by a condition (x > 44 & x < 49), which actually is not correct. If you have (x > 44 & x < 49) there, that means you will execute that statement, and ti = (x-44)*(i_ti_12(49))/(49-44) + (49-x)*(i_ti_12(44))/(49-44) is something independent with your if-else structure.

In that case, when you call i_ti_12(49), your function does not know when the recursion should be terminated since you did not define that case.

You can try the code below:

i_ti_12 <- function(x){
  if (x <= 44)
  {ti = exp(-13.2238 + 0.152568*x)}
  else if (x >= 49)
  {ti = -0.01245109 + 0.000315605*x}
  else
  {ti = (x-44)*(i_ti_12(49))/(49-44) + (49-x)*(i_ti_12(44))/(49-44)}
  return(ti)
}

such that

> i_ti_12(49)
[1] 0.003013555
Sign up to request clarification or add additional context in comments.

4 Comments

Wow! It works! Could you explain why it works after removing the final condition?
@Hillary see some of my explanation, hope it is helpful
@ThomaslsCoding This makes sense! Thanks a lot! Do you know why R function is so clear that it can recognize its conditional output? In this case, does R function run the first condition and save the return(ti) and then run the second condition and save the corresponding return, and then to the third condition?
@Hillary the statement is executed as long as the corresponding condition is met, and then exits if-else control flow and moves to return(ti)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.