0

If the function is nonlinear, there should be a starting value that the percentage is calculated from.

x <- -2
get_y <- function(x) {
  y <- xˆ2
}
get_z <- function(x) {
  z <- get_y(x) * x
}
get_result <- function(x) {
  get_z(x)
}

I want to get a value that indicates what happens to z in % if we change x from -2 by 1%.

What do I need to do with get_result(x) to get that?

Bonus: how would I create a dataframe of x and z values from these?

Victor Nielsen
  • 443
  • 2
  • 14
  • 1
    This is very unclear. Is the `y` in your second function (`get_z`) supposed to be the `y` from `get_y`? If so, `z` would simply be `z <- x ^ 2 * x` = `z <- x * 3`. But if you are looking at the percentage change in `y`, why do you even need the `z` calculations at all? Could you clarify what you are trying to do and add expected output? – jpsmith May 31 '23 at 13:30
  • So I wrote one thing wrong, and I corrected it now in the text. And you are right, I could just do `z <- x ^ 2 * x`, but this is just an example. In my real code it is useful to split it up into two functions. I might have written some things in a weird way, but the gist is that I want to see what happens to z in % terms if I change x by 1%. – Victor Nielsen May 31 '23 at 15:14
  • @jpsmith I also made the code more intuitive. – Victor Nielsen May 31 '23 at 15:23

1 Answers1

1

This should work. Each function needs to return something, and the get_result function should return how much z changes if you change x by pct_change

get_y <- function(x) {
  x ^ 2
}

get_z <- function(x) {
  get_y(x) * x
}
get_result <- function(x, pct_change = 0.01) {
  z_orig <- get_z(x)
  z_new <- get_z((1 + pct_change)*x)
  
  (z_new - z_orig)/z_orig
  
}

get_result_df <- function(x, pct_change){
  
  data.frame(x = x,
             z = get_z(x),
             x_pct_change = pct_change,
             z_pct_change = get_result(x, pct_change))
  
}

Here's an example:

get_result_df(x = -2, pct_change = 0.01)
#    x  z x_pct_change z_pct_change
# 1 -2 -8         0.01     0.030301
bouncyball
  • 10,631
  • 19
  • 31