Solve a function in R similar to Goal Seeker in Excel
Asked Answered
T

1

7

I saw already a similar question, but I can´t figure out, how to do. Maybe you can help.

Back solving a function or goal seek in R

ES <- function(y, z){-y * (1-pnorm(y/z)) + z * dnorm(y/z)} # = x
ES(906.19, 707.1) #33.47587

What I want is to solve for y, so z and x (33.4) is known. I have seen the solve and optim function, but I am not able to get the expected result.

Thanks!

Truism answered 18/7, 2018 at 13:12 Comment(1)
I'm not sure why the down-votes. OP has asked a perfectly fine question with a clear problem statement and reproducible code.Prowler
P
10

We can use uniroot to find the root of ES(y, z) - x for y given values z = 707.1 and x = 33.4.

ES <- function(y, z) -y * (1 - pnorm(y / z)) + z * dnorm(y / z)
res <- uniroot(function(x, y, z) ES(y, z) - x, c(0, 1000), z = 707.1, x = 33.4)

The solution for y is then

res$root
#[1] 906.9494

We confirm that E(y, z) = x

ES(res$root, 707.1)
#[1] 33.4
Prowler answered 18/7, 2018 at 13:42 Comment(2)
That´s exactly what I was searching for. Thank you! I did not expect to get an answer after the downvotes...Truism
You're very welcome @Sven. Don't worry about the down-votes and do stick around:-)Prowler

© 2022 - 2024 — McMap. All rights reserved.