R:产生混合物分布的功能 [英] R : function to generate a mixture distribution

查看:125
本文介绍了R:产生混合物分布的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从混合分布中生成样本

I need to generate samples from a mixed distribution

  • 40%的样本来自高斯(mean = 2,sd = 8)

  • 40% samples come from Gaussian(mean=2,sd=8)

20%的样本来自柯西(location = 25,scale = 2)

20% samples come from Cauchy(location=25,scale=2)

40%的样本来自高斯(平均值= 10,sd = 6)

40% samples come from Gaussian(mean = 10, sd=6)

为此,我编写了以下函数:

To do this, i wrote the following function :

dmix <- function(x){
prob <- (0.4 * dnorm(x,mean=2,sd=8)) + (0.2 * dcauchy(x,location=25,scale=2)) + (0.4 * dnorm(x,mean=10,sd=6))
return (prob)
}

然后通过以下方式进行测试:

And then tested with:

foo = seq(-5,5,by = 0.01)
vector = NULL
for (i in 1:1000){
vector[i] <- dmix(foo[i])
}
hist(vector)

我正在得到这样的直方图(我知道这是错误的)-

I'm getting a histogram like this (which I know is wrong) -

我做错了什么?任何人都可以给我一些指点吗?

What am I doing wrong? Can anyone give some pointers please?

推荐答案

当然还有其他方法可以实现,但是 distr 软件包使该操作非常简单. (另请参阅此答案作为另一个示例,以及有关 distr 和朋友的更多详细信息).

There are of course other ways to do this, but the distr package makes it pretty darned simple. (See also this answer for another example and some more details about distr and friends).

library(distr)

## Construct the distribution object.
myMix <- UnivarMixingDistribution(Norm(mean=2, sd=8), 
                                  Cauchy(location=25, scale=2),
                                  Norm(mean=10, sd=6),
                                  mixCoeff=c(0.4, 0.2, 0.4))
## ... and then a function for sampling random variates from it
rmyMix <- r(myMix)

## Sample a million random variates, and plot (part of) their histogram
x <- rmyMix(1e6)
hist(x[x>-100 & x<100], breaks=100, col="grey", main="")

如果您只想直接查看混合物分布的pdf,请执行以下操作:

And if you'd just like a direct look at your mixture distribution's pdf, do:

plot(myMix, to.draw.arg="d") 

这篇关于R:产生混合物分布的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆