[R] fitting truncated normal distribution
Sundar Dorai-Raj
sundar.dorai-raj at pdf.com
Wed Aug 16 17:12:07 CEST 2006
aon.912182281.tmp at aon.at wrote:
> Hello,
> I am a new user of R and found the function dtnorm() in the package msm.
>
> My problem now is, that it is not possible for me to get the mean and sd out of a sample when I want a left-truncated normal distribution starting at "0".
>
> fitdistr(x,dtnorm, start=list(mean=0, sd=1))
>
> returns the error message
> "Fehler in "[<-"(`*tmp*`, x >= lower & x <= upper, value = numeric(0)) : nichts zu ersetzen"
>
> I don't know, where to enter the lower/upper value. Is there a possibility to program the dtnorm function by myself?
>
> Thank you very much in advance for your help,
> markus
>
> -------------------------------------------
> Versendet durch aonWebmail (webmail.aon.at)
>
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
Hi, Markus,
You should always supply the package name where dtnorm is located. My
guess is most don't know (as I didn't) it is part of the msm package.
Also, you should supply a reproducible example so others may understand
your particular problem. For example, when I ran your code on data
generated from "rtnorm" (also part of msm) I got warnings related to the
NaNs generated in pnorm and qnorm, but no error as you reported. Both of
these suggestions are in the posting guide (see signature above).
So, to answer your problem, here's a quick example.
library(MASS) ## for fitdistr
library(msm) ## for dtnorm
dtnorm0 <- function(x, mean = 0, sd = 1, log = FALSE) {
dtnorm(x, mean, sd, 0, Inf, log)
}
set.seed(1) ## to others may reproduce my results exactly
x <- rtnorm(100, lower = 0)
fitdistr(x, dtnorm0, start = list(mean = 0, sd = 1))
Note, the help page ?fitdistr suggests additional parameters may be
passed to the density function (i.e. dtnorm) or optim. However, this
won't work here because "lower" is an argument for both functions. This
is the reason for writing dtnorm0 which has neither a lower or an upper
argument.
HTH,
--sundar
More information about the R-help
mailing list