R 如何绘制函数的概率密度函数?
假设A服从指数分布;B服从伽马分布R 如何绘制函数的概率密度函数?,r,R,假设A服从指数分布;B服从伽马分布 如何绘制0.5*(A+B)的PDF我不是R程序员,但知道对于具有PDF f1(x)和f2(x)的独立随机变量,PDF 由两个输入PDF的卷积f1*f2(x)给出两个变量之和的最大值 这里是在R中进行卷积(Jim Lewis提到)的一次尝试。请注意,可能有更有效的方法 lower <- 0 upper <- 20 t <- seq(lower,upper,0.01) fA <- dexp(t, rate = 0.4) fB <- d
如何绘制0.5*(A+B)的PDF我不是R程序员,但知道对于具有PDF f1(x)和f2(x)的独立随机变量,PDF
由两个输入PDF的卷积f1*f2(x)给出两个变量之和的最大值 这里是在R中进行卷积(Jim Lewis提到)的一次尝试。请注意,可能有更有效的方法
lower <- 0
upper <- 20
t <- seq(lower,upper,0.01)
fA <- dexp(t, rate = 0.4)
fB <- dgamma(t,shape = 8, rate = 2)
## C has the same distribution as (A + B)/2
dC <- function(x, lower, upper, exp.rate, gamma.rate, gamma.shape){
integrand <- function(Y, X, exp.rate, gamma.rate, gamma.shape){
dexp(Y, rate = exp.rate)*dgamma(2*X-Y, rate = gamma.rate, shape = gamma.shape)*2
}
out <- NULL
for(ix in seq_along(x)){
out[ix] <-
integrate(integrand, lower = lower, upper = upper,
X = x[ix], exp.rate = exp.rate,
gamma.rate = gamma.rate, gamma.shape = gamma.shape)$value
}
return(out)
}
fC <- dC(t, lower=lower, upper=upper, exp.rate=0.4, gamma.rate=2, gamma.shape=8)
## plot the resulting distribution
plot(t,fA,
ylim = range(fA,fB,na.rm=TRUE,finite = TRUE),
xlab = 'x',ylab = 'f(x)',type = 'l')
lines(t,fB,lty = 2)
lines(t,fC,lty = 3)
legend('topright', c('A ~ exp(0.4)','B ~ gamma(8,2)', 'C ~ (A+B)/2'),lty = 1:3)
lower如果你只是在寻找快速图形,我通常会采用快速脏模拟的方法。我画了一些画,在画上猛击高斯密度,画出那个坏男孩:
numDraws <- 1e6
gammaDraws <- rgamma(numDraws, 2)
expDraws <- rexp(numDraws)
combined <- .5 * (gammaDraws + expDraws)
plot(density(combined))
numDraws使用“Disr”软件包,这是相当直接的:
库(发行版)
A不必费心从函数中生成数据,只需绘制函数即可。使用curve()而不是line(),add=TRUE。这很好。我不熟悉发行包。
library(distr)
A <- Exp(rate=3)
B <- Gammad(shape=2, scale=3)
conv <- 0.5*(A+B)
plot(conv)
plot(conv, to.draw.arg=1)