Search code examples
rprobability

I have a joint PMF in matrix form. How to use R to find $P(N > G)$?


I've just started learning R, and I'm attempting to do some calculations involving a joint PMF in R.

The following matrix holds the joint PMF $p_{NG}(n,g)$:

(pNG <- matrix(c(16, 0, 0, 0, 0, 8, 8, 0, 0, 0, 4, 8, 4, 
                 0, 0, 2, 6, 6, 2, 0, 1, 4, 6, 4, 1)/80, 
               ncol = 5, nrow = 5, byrow = TRUE))

colnames(pNG) <- rownames(pNG) <- 0:4

The marginal PMFs of $N$ and $G$ are found as follows:

(pN <- rowSums(pNG))
(pG <- colSums(pNG))

The expected value and variance of $N$ are found as follows:

(EN <- sum(0:4 * pN))
(VarN <- sum((0:4 - EN)^2 * pN))

The conditional PMF of $N$ at $G = 0, 1, 2, 3, 4$ are found as follows:

(pNgG <- sweep(pNG, 2, pG, "/"))

The expected value of $N$ given $G$ are found as follows:

(ENgG <- colSums(0:4 * pNgG))

The variance of $N$ given $G$ is found as follows:

(VarNgG <- colSums(outer(0:4, ENgG, "-")^2 * pNgG))

With all this said and done, I want to find $P(N > G)$. However, I'm unsure of how to do this. I was thinking that there is a pattern here that has to do with the diagonals (upper or lower) of the matrix, since this is where $i > j$ or $j > i$; on the diagonals, we have $i = j$..


Solution

  • So you need to add up all the cells of the matrix where the row number is greater than the column number. This is the "lower triangular" sub-matrix, which you can access using R's lower.tri() function:

    sum(pXY[lower.tri(pXY)])
    

    You can use upper.tri() for the opposite. (And diag() if you need the diagonal, where the row number equals the column number.)