Diana
Diana

Reputation: 363

Product of two random variables in R using the discreteRV package

I am trying to compute the product of two random variables X and Y, but X * Y gives me the same result as 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

Upvotes: 0

Views: 408

Answers (1)

jcken
jcken

Reputation: 495

As Stéphane Laurent said, it might not be possible to compute f(X,Y) directly using the randomRV package. However we can compute each possible X*Y as well as their probabilities. These can then be stored as random variable. This solution might not be optimal but it seems to work.

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

You can then see

> XtimesY
Random variable with 3 outcomes

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

gives the distribution of X*Y.

Upvotes: 1

Related Questions