Calculate the covariance matrix from the list of occurrences

I have the following data frame:

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

I would like to calculate the covariance of the values cg. I believe that I can get it using cov()the following matrix, where each cell counts the number of matches between the two values 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

What is the fastest way to go from my_datato my_matrix? Remember that it cgcontains over 700 unique values.

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

Here is the code to generate 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))
-1
source share
1 answer

We can use crossprodwithtable

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
+1
source

Source: https://habr.com/ru/post/1675956/


All Articles