1

I need to build a cross product matrix based the product of a binary map.

The binary map is constructed as follows

A_ID<-c(111,116,111,112,112,114,116,113,114,111,114,116,115,116,116)
U_ID<-c(221,221,222,222,223,223,223,224,224,225,225,225,226,226,226)

df_u_a<-data.frame(U_ID,A_ID)

myTab <- table(df_u_a) # count
myTab[] <- as.integer(as.logical(myTab)) # binary map

The output of myTab[] is as follows:

     A_ID
U_ID  111 112 113 114 115 116
  221   1   0   0   0   0   1
  222   1   1   0   0   0   0
  223   0   1   0   1   0   1
  224   0   0   1   1   0   0
  225   1   0   0   1   0   1
  226   0   0   0   0   1   1

The cross product I need to do is as follows:

item.111<-c(myTab[][,1])
item.112<-c(myTab[][,2])    
crossprod(item.111, item.112)/sqrt(crossprod(item.111) * crossprod(item.112))

This gives me an output of 0.4082483 which I can build a matrix as follows enter image description here

In the image above I'm just illustrating the one value that I have calculated, but I need to calculate the rest for over 900 rows/columns in the matrix.

Any ideas on how I can build this cross product in R?

4

1 回答 1

3

您想要的矩阵是myTab不使变量居中的相关矩阵。因此,我们可以通过以下方式获得它:

crossprod(myTab %*% diag(1 / sqrt(colSums(myTab^2))))
#           [,1]      [,2]      [,3]      [,4] [,5]      [,6]
# [1,] 1.0000000 0.4082483 0.0000000 0.3333333  0.0 0.5773503
# [2,] 0.4082483 1.0000000 0.0000000 0.4082483  0.0 0.3535534
# [3,] 0.0000000 0.0000000 1.0000000 0.5773503  0.0 0.0000000
# [4,] 0.3333333 0.4082483 0.5773503 1.0000000  0.0 0.5773503
# [5,] 0.0000000 0.0000000 0.0000000 0.0000000  1.0 0.5000000
# [6,] 0.5773503 0.3535534 0.0000000 0.5773503  0.5 1.0000000
于 2018-03-20T13:34:46.067 回答