简体   繁体   English

如何从 R 中已知密度函数的分布中生成随机值?

[英]How to generate random values from a distribution with known density function in R?

I am given Zi's (i = 1,2...) form a sequence of iid variables with density function:我得到 Zi's (i = 1,2...) 形成具有密度函数的 iid 变量序列:

fZ(z) = P(S1 > z)/E(S1) fZ(z) = P(S1 > z)/E(S1)

Given that i know S1 follows a Pareto(1.7,70) distribution and E(S1) is equal to 100, how would i use R to obtain/generate random values of Z?鉴于我知道 S1 遵循 Pareto(1.7,70) 分布并且 E(S1) 等于 100,我将如何使用 R 来获取/生成 Z 的随机值? Like we all know how to generate random values of a normal distribution by using rnorm(), but what if our density was custom such as above?就像我们都知道如何使用 rnorm() 生成正态分布的随机值一样,但是如果我们的密度是自定义的,如上面那样怎么办? How would I simulate values that fit that distribution?我将如何模拟适合该分布的值?

Thank you谢谢

Let us start with the Pareto(1.7,70) .让我们从Pareto(1.7,70)

library(EnvStats)

custom_density <- function(z, location, shape) {
  stopifnot(shape > 1)
  ExpectS <- location * shape
  ExpectS <- ExpectS / (shape - 1)
  #' this should be equal to 100
  # print(ExpectS)

  (1 - EnvStats::ppareto(z, location = location, shape = shape)) /
    ExpectS
    # 100
}

custom_density(10, shape = 1.7, location = 70)

This is how I'm interpreting your custom density.这就是我解释您的自定义密度的方式。

plot.new()
curve(
  custom_density(x, shape = 1.7, location = 70),
  xlim = c(-2500,1000))
curve(dgamma(x, shape = 0.6, scale = 300), xlim = c(0, 1000), add = TRUE)

自定义密度+手工挑选

This is how the custom density looks like, and also we can relate it to something more common, like the gamma.这就是自定义密度的样子,我们也可以将它与更常见的东西联系起来,比如伽玛。 I picked parameters until the two curves were similar enough.我选择参数直到两条曲线足够相似。

Then I decided on rejection-sampling as the way to sample from this.然后我决定拒绝采样作为从中采样的方式。

There is a package that facilitates this {AR} :有一个包可以促进这个{AR}

library(AR)

AR::AR.Sim(
  100,
  f_X = function(x) custom_density(x, shape = 1.7, location = 70),
  Y.dist = "gamma",
  Y.dist.par = c(shape = 0.6, rate = 1/300)
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM