从事件列表中计算协方差矩阵 [英] Compute covariance matrix from list of occurrences

查看:117
本文介绍了从事件列表中计算协方差矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数据框:

# my_data
id  cg
1   a
2   b
3   a
3   b
4   b
4   c
5   b
5   c
5   d
6   d

我想计算 cg <的值的协方差/ code>。我相信我可以通过在以下矩阵上使用 cov()来获得它,其中每个单元格都计算两个 cg值之间的共现次数

I would like to compute the covariance of the values of cg. I believe I can obtain it by using cov() on the following matrix, where every cell counts the number of co-occurrences between two values of cg.

# my_matrix
cg  a  b  c  d
a   2  1  0  0
b   1  4  2  1
c   0  2  2  1
d   0  1  1  2

my_data my_matrix 最快的方法是什么?请注意, cg 包含700多个唯一值。

What is the quickest way to go from my_data to my_matrix? Please be aware that cg contains more than 700 unique values.

如果有更好的生成协方差的方法矩阵,我对此也很感兴趣。

If there is a better way to generate the covariance matrix, I am also interested in that.

这是生成 my_data

my_data <- structure(list(id = c(1L, 2L, 3L, 3L, 4L, 4L, 5L, 5L, 5L, 6L),
                          cg = c("a", "b", "a", "b", "b", "c", "b", "c", "d", "d")),
                     .Names = c("id", "cg"),
                     class = "data.frame", row.names = c(NA, -10L))


推荐答案

我们可以使用 crossprod table

crossprod(table(my_data))
#    cg
#cg  a b c d
#  a 2 1 0 0
#  b 1 4 2 1
#  c 0 2 2 1
#  d 0 1 1 2

这篇关于从事件列表中计算协方差矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆