[英]How to calculate multivariate normal distribution function in R
這是我嘗試的,使用mvtnorm包
library(mvtnorm)
set.seed(2357)
df <- data.frame(
x = rnorm(1000, mean=80, sd=20),
y = rnorm(1000, mean=0, sd=5),
z = rnorm(1000, mean=0, sd=5)
)
head(df)
x y z
1 70.38 1.307 0.2005
2 59.76 5.781 -3.5095
3 54.14 -1.313 -1.9022
4 79.91 7.754 -6.2076
5 87.07 1.389 1.1065
6 75.89 1.684 6.2979
# Get the dimension means and correlation matrix
means <- c(x=mean(df$x), y=mean(df$y), z=mean(df$z))
corr <- cor(df)
# Check P(x <= 80)
sum(df$x <= 80)/nrow(df) # 0.498
pmvnorm(lower=-Inf, upper=c(80, Inf, Inf), mean=means, corr=corr) # 0.8232
為什么擬合結果為0.82? 我哪里做錯了?
首先,您不需要模擬任何東西來研究pmvnorm
函數:
pmvnorm(lower=rep(-Inf, 3), upper=c(80, Inf, Inf), mean=c(80,0,0), corr=diag(rep(1,3)))
結果是0.5
,如您所料。
你的均值向量約為(79, 0, 0)
,所以讓我們試試吧:
pmvnorm(lower=rep(-Inf, 3), upper=c(80, Inf, Inf), mean=c(79,0,0), corr=diag(rep(1,3)))
結果現在是0.8413447
。 沒有任何問題。 通過僅指定相關矩陣,您告訴軟件假設所有方差都是一致的。 在模擬中,方差分別為400,25和25:與您在參數中指定的方差非常不同!
正確的計算使用數據的協方差矩陣,而不是其相關矩陣:
pmvnorm(lower=rep(-Inf, 3), upper=c(80, Inf, Inf), mean=means, sigma=cov(df))
結果是0.5178412
,與數據保持一致。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.