-1

I'm trying to fit my data to a regression model as follows : y=betaMu+betaA*Xa+betaD*Xd+si where si is an error term with a normal distribution. I wrote the code below, where phen[,2] is data for y , data.xa[,1] is Xa and data.xd[,1] is Xd:

library(stats4)
ll <- function(betaM,betaA,betaD, mu, sigma){
  R= phen[,2]-betaM-betaA*data.xa[,1]-betaD*data.xd[,1]
  R = suppressWarnings(dnorm(R, mu, sigma, log=TRUE))
  -sum(log(R))
}
fit <- mle(ll,start = list(betaM = 1, betaA = 1,betaD=1 ,mu = -1, sigma=1.5))

but I keep getting this error :

Error in optim(start, f, method = method, hessian = TRUE, ...) : initial value in 'vmmin' is not finite In addition: Warning message: In log(R) : NaNs produced

Can anyone help me fix this?

Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
pegahT
  • 59
  • 1
  • 8
  • 1
    When you evaluate `ll()` at your initial values, what do you get? – Gregor Thomas Dec 04 '19 at 19:40
  • well I'm very new to coding with R . when calling ll with different initial values for betaM , betaA &betaD I get this warning: In log(R) : NaNs produced – pegahT Dec 04 '19 at 20:29
  • If @Gregor's comment doesn't clear things up for you, then we need to see a [mcve] before we can get any further ... – Ben Bolker Dec 04 '19 at 20:30

1 Answers1

1

You seem to be computing the logarithm of the log-likelihood (i.e., taking the log twice, presumably by accident). If any of your probability densities are < 1, then the log-density will be negative, and taking the log of the log-density will give NaN. Instead of

R = suppressWarnings(dnorm(R, mu, sigma, log=TRUE))
-sum(log(R))

, try

LL <- dnorm(R, mu, sigma, log=TRUE)
-sum(LL)

Also: (1) it's bad practice to suppress warnings unless you absolutely can't find a way to avoid them; (2) it's probably confusing to re-assign the value of R (although harmless in this case).

Ben Bolker
  • 211,554
  • 25
  • 370
  • 453