R : "argument is missing, with no default "

12,220

The documentation in help("optim") says (emphasis added by me):

fn
A function to be minimized (or maximized), with first argument the vector of parameters over which minimization is to take place. It should return a scalar result.

Thus, this works:

somme <- function(par){
  k <- par[[1]]
  h <- par[[2]]
  s <- par[[3]]
  out <- (P(A(1,k,h,s), B(1,k), -0.002)-1.0021)^2+
    (P(A(2,k,h,s), B(2,k), -0.0016)-1.0036)^2+
    (P(A(3,k,h,s), B(3,k), -0.001)-1.0038)^2+
    (P(A(4,k,h,s), B(4,k), -0.0002)-1.002)^2+
    (P(A(5,k,h,s), B(5,k), 0.00077)-0.9976)^2+
    (P(A(6,k,h,s), B(6,k), 0.0019)-0.9901)^2+
    (P(A(7,k,h,s), B(7,k), 0.0031)-0.9796)^2+
    (P(A(8,k,h,s), B(8,k), 0.0044)-0.9655)^2+
    (P(A(9,k,h,s), B(9,k), 0.0056)-0.9494)^2+
    (P(A(10,k,h,s), B(10,k), 0.0067)-0.9317)^2
  return(out)
}

init <- c(k = 1, h = 1, s = 1)
result <- optim(par = init, fn = somme)

PS: You seem to be a masochist who likes excessive typing.

Share:
12,220
Dadoo
Author by

Dadoo

Updated on June 04, 2022

Comments

  • Dadoo
    Dadoo almost 2 years

    I am running the following code to minimize a function thanks to optim() in R but I have the following message : "argument "h" is missing, with no default".

    I checked on previous messages where it is said that it is often a comma before a parenthesis, but does not seem to be the case in my code.

    Could you please help me to understand what to do ? Thank you very much.

    Here is the code :

    A<-function(t,k,h,s){
      out<-exp((h-(s*s/(2*k*k)))*(B(t,k)-t)-(s*s/(4*k))*(B(t,k)^2))
      return(out)
    }
    
    B<-function(t, k){
      out<-(1-exp(-k*t))/k
      return(out)
    }
    
    P<-function(a, b, r){
      out<-a*exp(-b*r)
      return(out)
    }
    
    somme<-function(k,h,s){
      out<-(P(A(1,k,h,s), B(1,k), -0.002)-1.0021)^2+(P(A(2,k,h,s), B(2,k), -0.0016)-1.0036)^2+(P(A(3,k,h,s), B(3,k), -0.001)-1.0038)^2+(P(A(4,k,h,s), B(4,k), -0.0002)-1.002)^2+(P(A(5,k,h,s), B(5,k), 0.00077)-0.9976)^2+(P(A(6,k,h,s), B(6,k), 0.0019)-0.9901)^2+(P(A(7,k,h,s), B(7,k), 0.0031)-0.9796)^2+(P(A(8,k,h,s), B(8,k), 0.0044)-0.9655)^2+(P(A(9,k,h,s), B(9,k), 0.0056)-0.9494)^2+(P(A(10,k,h,s), B(10,k), 0.0067)-0.9317)^2
      return(out)
    }
    
    init<-c(k=0,h=0,s=0)
    result<-optim(par=init, fn=somme)
    result