Fitting truncnorm distribution with distrplus causes fatal error (R crashes)

Viewed 184

Here's the code that crashes R for me without any useful error messages. Any ideas? I'm going crazy over here. Thanks,

library(fitdistrplus)
library(truncnorm)
set.seed(0)
x = rtruncnorm(n=30, a=0, b=Inf, mean=1, sd=0.45)
my_fit = fitdist(x, "truncnorm", method='mle', fix.arg=list(a=0, b=Inf), 
                 start=list(mean=mean(x), sd=sd(x)))
2 Answers

As part of its machinery, fitdist calls the specified density function with an x argument of numeric(0). This crashes dtruncnorm, which calls C++ code which isn't expecting that ...

dtruncnorm(numeric(0))

is a way to get to the same crash quicker. I tried to hack my way around this by creating my own dtruncnorm() wrapper:

dtruncnorm <- function(x,a,b,mean,sd) {
    if (length(x)==0) numeric(0) else truncnorm::dtruncnorm(x, a,b,mean,sd)
}

but so far it's still crashing somewhere farther along the line.

It would be community-minded to contact the maintainer of dtruncnorm/file an issue here ...

Once Ben Bolker identified that truncnorm - not fitdist - is the issue, I decided to simply use a different library. The following code executes just fine for me:

library(fitdistrplus)
library(extraDistr)
set.seed(0)
x = rtnorm(n=30, a=0, b=Inf, mean=1, sd=0.45)
my_fit = fitdist(x, "tnorm", method='mle', fix.arg=list(a=0, b=Inf), 
                 start=list(mean=mean(x), sd=sd(x)))
Related