Error in f(x, ...) : argument "x" is missing, with no default in nlm

r nlm
Ab2016 picture Ab2016 · May 2, 2017 · Viewed 11.8k times · Source
rm(list=ls(all=TRUE))
data <- read.csv("con.csv", header=TRUE, sep = ",")
x <- data$X0
n = length(x); T1 <- 1
f <- function(a,b) {
  L <- (n*log(a))+(n*a*log(T1))+(n*a*log(b))-(n*log((T1^a)-(b^a)))- ((a+1)*sum(log(b+x)))
  return(-L)  
}

ML <- nlm(f, c(0.01,0.17))

Result in Error in f(x, ...): argument "x" is missing, with no default help me to figure out error and solution to solve it out

Answer

Marco Sandri picture Marco Sandri · May 2, 2017

The argument passed to the function f must be a single vector. Here is the correct definition:

f <- function(pars) {
  L <- (n*log(pars[1]))+(n*pars[1]*log(T1))+(n*pars[1]*log(pars[2]))-
       (n*log((T1^pars[1])-(pars[2]^pars[1])))- ((pars[1]+1)*sum(log(pars[2]+x)))
  return(-L)  
}

and a working example:

set.seed(1234)
n <- 100
x <- runif(n)+5
T1 <- 1
(ML <- nlm(f, p=c(0.01,0.17)))

The result is:

$minimum
[1] 227.3527

$estimate
[1] 2.420050e-07 1.768907e-01

$gradient
[1]  259.0327 -308.4809

$code
[1] 2

$iterations
[1] 12