Reputation: 329
I am going to use a very simple example to explain my problem (the real problem concerns a very complex univariate function). Consider the following univariate function
f <- function(x, p){ 10 - (x - p)^2 }
where p belongs to {-500, -499,..., -1, 0, 1,..., 499, 500}.
I would like to find the value of x that maximizes f, for each value of p. This translates into 1001 values of x.
I know that one can do that in R-software with i) a for-loop, ii) a while-loop, iii) the function apply, and iv) the function foreach (doParallel package). However, I was wondering if you could tell me whether there is a more efficient way to solve the above optimization problem in R-software, please.
I know the above optimization problem is trivial to solve. However, the question focuses on an efficient procedure to solve several optimization problems simultaneously in R.
Thank you very much for your help.
Upvotes: 2
Views: 498
Reputation: 2829
The function optimize()
can be used to get the maximum value of a function.
Then, you can lapply over the values of the parameters as following:
p<-seq(-500,500,1)
fn <- function(param,p,...){return( 10 - (param - p)^2) }
ll <- lapply(pp,function(i)
optimize(f= fn,
par =c(-1000),
p=i,
interval = c(-100000000,1000000000),
maximum = TRUE))
ll[[which.max(sapply(ll,'[[','maximum'))]]
Upvotes: 2