Search code examples
rprobability

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?


Solution

  • 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