Hi fellow R users, I am desperately hoping there is an easy way to do this in R. Say I have three functions: f(x) = x^2 f(y) = 2y^2 f(z) = 3z^2 constrained such that x+y+z=c (let c=1 for simplicity). I want to find the values of x,y,z that will minimize f(x) + f(y) + f(z). I know I can use the optim function when there is only one function, but don't know how to set it up when there are three. I would also like to apply this to higher dimensions (i.e. for more than three functions) if possible. Thank you for all your help! -- Kind regards, Linh Tran, MPH
finding the values to minimize sum of functions
3 messages · Linh Tran, Joshua Wiley, Petr Savicky
Hi Linh,
Here is an approach:
f <- function(v) {
v <- v/sum(v)
(v[1]^2) + (2 * v[2]^2) + (3*v[3]^2)
}
(res <- optim(c(.6, .3, .1), f))
res$par/sum(res$par)
This is a downright lazy way to implement the constraint. The main
idea is to combine all three functions into one function that takes a
vector of parameters (v, in this case).
Cheers,
Josh
On Thu, Jul 19, 2012 at 10:24 AM, Linh Tran <Tranlm at berkeley.edu> wrote:
Hi fellow R users, I am desperately hoping there is an easy way to do this in R. Say I have three functions: f(x) = x^2 f(y) = 2y^2 f(z) = 3z^2 constrained such that x+y+z=c (let c=1 for simplicity). I want to find the values of x,y,z that will minimize f(x) + f(y) + f(z). I know I can use the optim function when there is only one function, but don't know how to set it up when there are three. I would also like to apply this to higher dimensions (i.e. for more than three functions) if possible. Thank you for all your help! -- Kind regards, Linh Tran, MPH
______________________________________________ R-help at r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
Joshua Wiley Ph.D. Student, Health Psychology Programmer Analyst II, Statistical Consulting Group University of California, Los Angeles https://joshuawiley.com/
On Thu, Jul 19, 2012 at 10:24:17AM -0700, Linh Tran wrote:
Hi fellow R users, I am desperately hoping there is an easy way to do this in R. Say I have three functions: f(x) = x^2 f(y) = 2y^2 f(z) = 3z^2 constrained such that x+y+z=c (let c=1 for simplicity). I want to find the values of x,y,z that will minimize f(x) + f(y) + f(z).
Hi. If the constraint is linear as in this case, it is possible to eliminate one of the varibles. Instead of minimizing x^2 + 2y^2 + 3z^2 under the constraint x+y+z = c, minimize, for example x^2 + 2y^2 + 3(c - x - y)^2 with no constraint. Hope this helps. Petr Savicky.