首页 > 解决方案 > R中两个随机变量的乘积,使用discreteRV包

问题描述

我正在尝试计算两个随机变量 X 和 Y 的乘积,但 X * Y 给我的结果与jointRV 相同。

XandY <-  jointRV(outcomes = list(c(0, 9), c(-3, 1)), probs = c(t(outer(c(1/2, 1/2), c(1/7, 6/7)))))
X <- marginal(XandY, 1)
Y <- marginal(XandY, 2)
> X * Y
Random variable with 4 outcomes

Outcomes 0,-3  0,1 9,-3  9,1
Probs    1/14  3/7 1/14  3/7
> XandY
Random variable with 4 outcomes

Outcomes 0,-3  0,1 9,-3  9,1
Probs    1/14  3/7 1/14  3/7

标签: r

解决方案


正如Stéphane Laurent所说,可能无法f(X,Y)直接使用randomRV包进行计算。然而,我们可以计算每一个可能X*Y以及它们的概率。然后可以将这些存储为随机变量。此解决方案可能不是最佳的,但似乎有效。

product.matrix <- t(outer(c(0, 9),c(-3, 1),"*")) ## find all possible products
probability.matrix <- t(outer(c(1/2, 1/2), c(1/7, 6/7)))
unique.products <- unique(as.vector(product.matrix))  ## find the unique products
probability.vector <- rep(0, length(unique.products))

for(i in 1:length(probability.vector)){

  z <- unique.products[i]

  indices <- which(as.vector(product.matrix) == z) ## find which elements of product.matrix match up to z

  probability.vector[i] <- sum(as.vector(probability.matrix)[indices]) ## sum their probabilities

}

XtimesY <- RV(outcomes = unique.products, probs = probability.vector) ## store as RV

然后你可以看到

> XtimesY
Random variable with 3 outcomes

Outcomes  -27    0    9
Probs    1/14  1/2  3/7

给出 的分布X*Y


推荐阅读