Search code examples
rfunctiondataframemathematical-optimizationminimization

minimization of a set of functions r


I need to find an efficient way to find the minimum of a set of homogeneous functions.

I am using the function stats::optimize

If I do it with one single function, no problem. However I need to change function parameters taking them from a dataframe and I can't find a way to let optimize process my set of functions. See code below

myfun <- function (x) {
  sqrt((x-3)^2 + (x-4)^2 + (x-5)^2)
}

optimize(myfun, c(0,10) 

no problems here.

However I need to substitute those numbers with each row of a data frame such as

df <- data.frame(matrix(c(2,7,8,4,9,10,5,4,2), nrow = 3, ncol =3))

something like:

v <-df[1, ]
myfun2 <- function (v) {
  function(x) sqrt((x-v[1])^2 + (x-v[2])^2 + (x-v[3])^2)
}

optimize(myfun2, c(0,10))

Error in optimize(myfun2, c(0, 10)) : 
  invalid function value in 'optimize'

optimize(myfun2(df[1, ]), c(0,10))
Error in optimize(myfun2(df[1, ]), c(0, 10)) : 
  invalid function value in 'optimize'

for a single case, that would eventually end up in a for loop for covering each row of the data frame

however optimize returns an error if I pass myfun2.

Sorry if this is a simple question, but I really cannot find the right way to solve it and any help would be very much appreciated.

I also I tried

m <- matrix(c(2,7,8,4,9,10,5,4,2), nrow = 3, ncol =3)
myfun2 <- function (v) {
  function(x) sqrt((x-m[1,1])^2 + (x-m[1,2])^2 + (x-m[1,3])^2)
}       
optimize(myfun2, c(0,10))

Error in optimize(myfun2, c(0, 10)) : 
  invalid function value in 'optimize'


Solution

  • The function that has to be used is the original myfun, with the numbers replaced by v[1], v[2] and v[3], called in an apply loop.

    myfun <- function (x, v) {
      sqrt((x - v[1])^2 + (x - v[2])^2 + (x - v[3])^2)
    }
    
    df <- data.frame(matrix(c(2,7,8,4,9,10,5,4,2), nrow = 3, ncol =3))
    
    res <- apply(df, 1, function(.v) optimize(myfun, c(0,10), v = .v))
    
    do.call(rbind, res)
    #     minimum  objective
    #[1,] 3.666648 2.160247 
    #[2,] 6.666666 3.559026 
    #[3,] 6.666667 5.887841