使用 R 生成密度对象的随机偏差

发布于 2024-08-04 15:09:47 字数 928 浏览 6 评论 0原文

我有一个像这样创建的密度对象 dd:

x1 <- rnorm(1000) 
x2 <- rnorm(1000, 3, 2) 
x <- rbind(x1, x2)
dd <- density(x) 
plot(dd)

它产生了这个非常非高斯分布:

alt text http://www.cerebralmastication.com/wp-content/uploads/2009/09/nongaus.png

我最终希望获得与 rnorm 类似的分布的随机偏差偏离正态分布。

我试图解决这个问题的方法是获取内核的 CDF,然后让它告诉我如果我向它传递累积概率(逆 CDF)的变量。这样我就可以将均匀随机变量的向量转换为密度的绘图。

看来我想做的事情应该是其他人在我之前做过的基本事情。有没有简单的方法或简单的功能来做到这一点?我讨厌重新发明轮子。

FWIW我找到了这篇R帮助文章但我不能明白他们在做什么,最终的输出似乎并没有产生我想要的结果。但这可能是我不明白的一步。

我考虑过使用 Johnson来自suppdists包的分布,但Johnson不会给我我的数据所具有的漂亮的双峰驼峰。

I have a density object dd created like this:

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

I would ultimately like to get random deviates from this distribution similar to how rnorm gets deviates from a normal distribution.

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

请叫√我孤独 2024-08-11 15:09:47

替代方法:

sample(x, n, replace = TRUE)

Alternative approach:

sample(x, n, replace = TRUE)
少钕鈤記 2024-08-11 15:09:47

这只是法线的混合。那么为什么不这样做呢:

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 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文