简体   繁体   English

计算R中联合概率质量函数的协方差

[英]Calculating covariance of joint probability mass function in R

I have a joint probability mass function of two variables X,Y like here 我有两个变量X,Y的联合概率质量函数,如下所示

在此处输入图片说明

How can I calculate the covariance in R? 如何计算R中的协方差?

I created two vectors x,y and fed them into cov(), but I get the wrong result. 我创建了两个向量x,y并将它们输入到cov()中,但是得到了错误的结果。

How can I do this right? 我该怎么做呢?

Thanks in advance and happy coding! 在此先感谢您,并祝您编程愉快!

Since SO is a coding forum, I'll leave working out the math/stats details up to you. 由于SO是一个编码论坛,因此我将由您自行确定数学/统计信息。 Here is an implementation in R. 这是R中的实现。

  1. We start by noting the sample spaces for X and Y 我们首先注意X和Y的样本空间

     # For G G <- 0:3; # For R R <- 0:2; 
  2. The joint probability mass function is given by the following matrix 联合概率质量函数由以下矩阵给出

     joint_pmf <- matrix( c(4/84, 12/84, 4/84, 18/84, 24/84, 3/84, 12/84, 6/84, 0, 1/84, 0, 0), ncol = 3, byrow = T); 
  3. We calculate the population means 我们计算人口平均值

     # For G mu_G <- rowSums(joint_pmf) %*% G; # For R mu_R <- colSums(joint_pmf) %*% R; 
  4. We can make use of the theorem Cov(X, Y) = E[XY] - E[X]E[Y] to calculate the covariance 我们可以利用定理Cov(X, Y) = E[XY] - E[X]E[Y]来计算协方差

     cov_GR <- G %*% joint_pmf %*% R - mu_G * mu_R; # [,1] #[1,] -0.1666667 

    where we have used the fact that E[G] = mu_G and E[R] = mu_R are the respective population means. 在这里我们使用了E[G] = mu_GE[R] = mu_R分别是总体平均值的E[R] = mu_R

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM