简体   繁体   中英

How to find the multivariate empirical cumulative distribution function (CDF) in R?

I have two correlated variables x and y, and I wonder how to find their empirical joint CDF in R?

Also, how can we find probabilities like: P(X<=2 and Y<=3), P(X>=2 and Y>=3), P(X>=3 and Y<=2), P(X<=3 and Y>=2); P(X<=2 or Y<=3), P(X>=3 or Y>=2), P(X>=3 or Y<=2), P(X<=2 or Y>=3)? Thanks for any help.

x= c(1,3,2,2,8,2,1,3,1,1,3,3,1,1,2,1,2,1,1,3,4,1,1,3,1,1,2,1,3,7,1,4,6,1,2,1,1,3,1,2,2,3,4,1,1,1,1,2,2,12,1,1,2,1,1,1,3,4)
y = c(1.42,5.15,2.52,2.29,12.36,2.82,1.49,3.53,1.17,1.03,4.03,5.26,1.65,1.41,3.75,1.09,3.44,1.36,1.19,4.76,5.58,1.23,2.29,7.71,1.12,1.26,2.78,1.13,3.87,15.43,1.19,4.95,7.69,1.17,3.27,1.44,1.05,3.94,1.58,2.29,2.73,3.75,6.80,1.16,1.01,1.00,1.02,2.32,2.86,22.90,1.42,1.10,2.78,1.23,1.61,1.33,3.53,10.44)

cor(x,y)
x_cdf = ecdf(x)
y_cdf = ecdf(y)

You can use the mltools package.

x <- c(1,3,2,2,8,2,1,3,1,1,3,3,1,1,2,1,2,1,1,3,4,1,1,3,1,1,2,1,3,7,1,4,6,1,2,1,1,3,1,2,2,3,4,1,1,1,1,2,2,12,1,1,2,1,1,1,3,4)
y <- c(1.42,5.15,2.52,2.29,12.36,2.82,1.49,3.53,1.17,1.03,4.03,5.26,1.65,1.41,3.75,1.09,3.44,1.36,1.19,4.76,5.58,1.23,2.29,7.71,1.12,1.26,2.78,1.13,3.87,15.43,1.19,4.95,7.69,1.17,3.27,1.44,1.05,3.94,1.58,2.29,2.73,3.75,6.80,1.16,1.01,1.00,1.02,2.32,2.86,22.90,1.42,1.10,2.78,1.23,1.61,1.33,3.53,10.44)

library(mltools)
library(data.table)

# set data in a data.table
dt <- data.table(x = x, y = y)

Example: P(X <= 3, Y <= 5) = ?

> empirical_cdf(dt, ubounds = data.table(x = 3, y = 5))
   x y N.cum       CDF
1: 3 5    47 0.8103448
> mean(x <= 3 & y <= 5) # same result
[1] 0.8103448

Now, say you want to calculate P(X > 3, Y <= 5) . Starting with the equality

P(X <= 3, Y <= 5) + P(X > 3, Y <= 5) = P(Y <= 5)

you get

P(X > 3, Y <= 5) = P(Y <= 5) - P(X <= 3, Y <= 5)

Then you calculate this probability as follows:

> empirical_cdf(dt$y, 5)$CDF - empirical_cdf(dt, data.table(x = 3, y = 5))$CDF
[1] 0.01724138
> mean(x > 3 & y <= 5) # same result
[1] 0.01724138

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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