简体   繁体   中英

How to compute the conditional probability in R?

Let's suppose I have these two vectors:

x = rnorm(20)
y = rnorm(20)

I want to compute the probability that y > 0 given that x > 0 . In other words, I want the frequency that my y > 0 when x > 0 . Can anyone show me how to code this in R?

To make the results reproducible, I will use set.seed

set.seed(42)
x = rnorm(20)
y = rnorm(20)

You can just subset the data to select the ones where x>0 and then count what proportion of those have y>0

PosX = which(x>0)
sum(y[PosX] > 0)/length(PosX)
[1] 0.6

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