Raa*_*aaj 6 r probability markov-chains mcmc mixture-model
我需要从混合分布中生成样本
40%的样本来自高斯(平均值= 2,sd = 8)
20%的样本来自Cauchy(位置= 25,比例= 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)
}
Run Code Online (Sandbox Code Playgroud)
然后测试:
foo = seq(-5,5,by = 0.01)
vector = NULL
for (i in 1:1000){
vector[i] <- dmix(foo[i])
}
hist(vector)
Run Code Online (Sandbox Code Playgroud)
我得到这样的直方图(我知道这是错的) -

我究竟做错了什么?谁能指点一下好吗?
当然还有其他方法可以做到这一点,但是distr包让它非常简单.(也看到这个答案的另一个例子,关于一些细节颇和朋友).
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="")
Run Code Online (Sandbox Code Playgroud)

如果您只想直接查看混合物分布的pdf,请执行以下操作:
plot(myMix, to.draw.arg="d")
Run Code Online (Sandbox Code Playgroud)

| 归档时间: |
|
| 查看次数: |
6589 次 |
| 最近记录: |