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?
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