这个双变量CDF情节看起来是否正确?

时间:2015-02-23 16:59:15

标签: r plot statistics

我通过整合其pdf计算了双变量标准正态分布的cdf(我的代码如下)。下面的情节看起来不错吗?

require(pracma) # r package for 2D integration

x <- c(8.29678, 21.87154, 21.97512, 23.57027, 25.79866, 28.90927, 28.96631, 
       29.35752, 31.30991, 31.44618, 31.93110, 31.97407, 32.67840, 33.41173, 
       33.95492, 34.16411, 34.18134, 34.19854, 34.56954, 34.84683, 35.69282, 
       35.83888, 36.77594, 37.45782, 38.57748, 38.68419, 39.39681, 9.96412, 
       40.58143, 40.99610, 42.53939, 43.48341, 45.03296, 45.31699, 45.36327, 
       45.72331, 46.27251, 47.46588, 48.05595, 48.88121, 49.33571, 50.46709, 
       50.84327, 53.07657, 40.83270, 59.86046)

y <- c(2.283034, 2.691600, 3.133521, 4.370813, 4.771603, 4.814870, 5.671189, 
       6.371071, 6.848534, 8.067521, 8.505044, 8.740460, 9.238722, 9.262792, 
       10.273220, 10.356793, 11.237900, 11.293111, 12.125125, 13.020383, 
       13.674205, 13.793084, 13.819244, 14.977113, 15.304603, 17.751326, 
       19.062926, 19.251928, 19.313849, 19.674649, 20.018303, 20.346346, 
       21.572090, 21.706065, 21.880892, 22.051557, 22.259324, 22.500936, 
       23.144220, 23.931346, 24.027882, 24.309860, 25.674655, 26.532192, 
       28.288739, 28.612735, 34.353527) 

mu1 <- mean(x)  # expected value of x
mu2 <- mean(y)  # expected value of y
sig1 <- sd(x)   # variance of x
sig2 <- sd(y)   # variance of y
rho <- cor(x, y)    # corr(x, y)

bivariate <- function(x,y)  { # bivariate pdf
  term1 <- 1 / (2 * pi * sig1 * sig2 * sqrt(1 - rho^2))
  term2 <- (x - mu1)^2 / sig1^2
  term3 <- -(2 * rho * (x - mu1)*(y - mu2))/(sig1 * sig2)
  term4 <- (y - mu2)^2 / sig2^2
  z <- term2 + term3 + term4
  term5 <- term1 * exp((-z / (2 *(1 - rho^2))))
  return (term5)
}

# bivariate cdf is the integration of bivariate pdf
cdf=c() # to store the value of cdf
for( i in 1:length(x)) {
  cdf[i]=quad2d(bivariate, x[i],x[i+1],y[i],y[i+1]) 
  # here x[i] and x[i+1] is lower and upper limits for the integaration of
  x variable
  # y[i] and y[i+1]  is also lower and upper limits for the integaration of      
  y variable 
}

z1 <- matrix(cdf[1:46],ncol=46,nrow=46) 
contour(x[1:46],y[1:46],z1)
persp(x[1:46],y[1:46], z1, main = "Bivariate Normal cdf" )  

fig

0 个答案:

没有答案