如何计算 R 中的条件概率?

How to compute the conditional probability in R?

假设我有这两个向量:

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

我想计算 y > 0 给定 x > 0 的概率。 换句话说,我想要 x > 0 时我的 y > 0 的频率。 谁能告诉我如何在 R 中编写代码?

为了使结果可重现,我将使用set.seed

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

您可以将数据子集化为 select x>0 的数据,然后计算其中 y>0 的比例

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