简体   繁体   English

使用R编写一个截断的正态分布函数

[英]Write a truncated normal distribution function using R

Hi I'm trying to use R to write a dtnorm () and rtnorm () function. 嗨,我正在尝试使用R编写dtnorm()和rtnorm()函数。 (the same ones in the msm package) (与msm软件包中的相同)

here is the code i wrote: 这是我写的代码:

rtnorm<-function(mu=0,sd=1,a=-Inf,b=Inf)
{
F<-runif(n=length(mu))
Fa<-pnorm((a-mu)/sd,0,sd=1)
Fa[a== -Inf] <-0
Fb<-pnorm((b-mu)/sd,0,sd=1)
Fb[b==Inf]<-1
y<-mu+sd*qnorm(F*(Fb-Fa)+Fa)
y
}

however, when I test it,it only gives me one number in return, but when I use the msm package, it gives me 10 different numbers in return. 但是,当我测试它时,它只给我一个数字,但是当我使用msm软件包时,它给了我10个不同的数字。 how should i modify this code? 我应该如何修改此代码?

It's because you set mu=0 . 这是因为您设置了mu=0 This has length of 1. Try setting mu=rep(0,10) to get back 10 numbers. 它的长度为1。尝试设置mu=rep(0,10)以获取10个数字。 For example: 例如:

rtnorm<-function(mu,sd=1,a=-Inf,b=Inf)
{
  F<-runif(n=length(mu))
  Fa<-pnorm((a-mu)/sd,0,sd=1)
  Fa[a== -Inf] <-0
  Fb<-pnorm((b-mu)/sd,0,sd=1)
  Fb[b==Inf]<-1
  y<-mu+sd*qnorm(F*(Fb-Fa)+Fa)
  y
}

rtnorm(mu=rep(0,10))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM