I'm trying to learn my way around R and I need a little help. Below is a little sample of the kind of problem I am working on.
myFunction <- function(price1) {
prices <- c(1:50)
prices[1] <- price1
recursiveA <- vector(length = 51)
recursiveA[1] <- 100
for (i in 1:50) {
recursiveA[i+1] <- 30*prices[i] + recursiveA[i]
}
target <- recursiveA[51]
return(target)
}
What I want to do is create a new function that will find the price1
value needed to yield a target
value. For example in this new function I would be able to set 47320
as a parameter and it would return 300
. In the first function, myFunction
, a value of 300
returns a value of 47320
.
How can I write a function in R to do this? Is there an existing function in R? I see through my Googling and searching on this site, a lot of people recommend the uniroot()
function or optimize()
. I can't figure out how to use that for something other than algebraic quadratics.
If it helps, I know that in excel I can solve this easily by using the goal seek tool. You can set a desired output and it finds the needed input from the formula(s) you define.
Please let me know if anything's unclear and I will try my best to explain further.
Any help is much appreciated. Thank you.