R : function to generate a mixture distribution

标签 r probability markov-chains mcmc mixture-model

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

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

  • 20% 的样本来自 Cauchy(location=25,scale=2)

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

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

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)
}

然后测试:

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

我得到了这样的直方图(我知道这是错误的)- histogram of the supposed distribution

我做错了什么?请问有人可以指点一下吗?

最佳答案

当然还有其他方法可以做到这一点,但是 distr 包使它变得非常简单。 ( See also this answer 是另一个示例以及有关 distr 和 friend 的更多详细信息)。

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="")

enter image description here

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

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

enter image description here

关于R : function to generate a mixture distribution,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23480529/

相关文章:

sql - 将 R randomForest 对象保存到 SQL 数据库

r - htmltab 找不到使用数字或字符向量作为 'which' 参数的表

r - 分配由概率分布通知的特定数量的值(在 R 中)

algorithm - 具有截止值的相对权重

algorithm - 简单(非隐藏)马尔可夫链的前向/后向算法

r - 改变闭包中的变量

Python 程序与人类玩家和计算机一起运行 pig 游戏

python - 字母尺度和随机文本上的马尔可夫链

python - 余弦波的贝叶斯拟合花费的时间比预期的要长

r - 如何使用非默认浏览器?