[英]Generate stochastic random deviates from a density object with R
I have a density object dd created like this: 我有一个像这样创建的密度对象dd:
x1 <- rnorm(1000)
x2 <- rnorm(1000, 3, 2)
x <- rbind(x1, x2)
dd <- density(x)
plot(dd)
Which produces this very non-Gaussian distribution: 这产生了这种非高斯分布:
alt text http://www.cerebralmastication.com/wp-content/uploads/2009/09/nongaus.png alt text http://www.cerebralmastication.com/wp-content/uploads/2009/09/nongaus.png
I would ultimately like to get random deviates from this distribution similar to how rnorm gets deviates from a normal distribution. 我最终希望得到这种分布的随机偏差,类似于rnorm如何偏离正态分布。
The way I am trying to crack this is to get the CDF of my kernel and then get it to tell me the variate if I pass it a cumulative probability (inverse CDF). 我试图解决这个问题的方法是获取我的内核的CDF,然后让它告诉我variate,如果我传递它的累积概率(反向CDF)。 That way I can turn a vector of uniform random variates into draws from the density. 这样我可以将均匀随机变量的矢量转换为密度的绘制。
It seems like what I am trying to do should be something basic that others have done before me. 看起来我想做的事情应该是其他人在我面前做的基本事情。 Is there a simple way or a simple function to do this? 这样做有简单的方法或简单的功能吗? I hate reinventing the wheel. 我讨厌重新发明轮子。
FWIW I found this R Help article but I can't grok what they are doing and the final output does not seem to produce what I am after. 我找到了这篇R帮助文章,但我无法理解他们正在做什么,最终的输出似乎没有产生我所追求的。 But it could be a step along the way that I just don't understand. 但它可能是我不明白的一步。
I've considered just going with a Johnson distribution from the suppdists package but Johnson won't give me the nice bimodal hump which my data has. 我已经考虑过从供应商套餐中选择Johnson发行版,但约翰逊不会给我一些我的数据所具有的漂亮的双峰驼峰 。
替代方法:
sample(x, n, replace = TRUE)
This is just a mixture of normals. 这只是法线的混合物。 So why not something like: 那么为什么不是这样的:
rmnorm <- function(n,mean, sd,prob) {
nmix <- length(mean)
if (length(sd)!=nmix) stop("lengths should be the same.")
y <- sample(1:nmix,n,prob=prob, replace=TRUE)
mean.mix <- mean[y]
sd.mix <- sd[y]
rnorm(n,mean.mix,sd.mix)
}
plot(density(rmnorm(10000,mean=c(0,3), sd=c(1,2), prob=c(.5,.5))))
This should be fine if all you need are samples from this mixture distribution. 如果你需要的只是来自这种混合物分布的样品,这应该没问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.