2016-02-29 133 views
-2

我有一些文件和其中的所有单词的矩阵。数字表示文档中出现此单词的次数。计算矩阵的相关性

| topic | word1 | word2 | word3 | word4 | word5 |... 
|----------|-------|-------|-------|-------|-------| 
| politics | 5  | 2  | 4  | 0  | 1  | 
| sports | 2  | 0  | 1  | 1  | 6  | 
| music | 2  | 3  | 1  | 3  | 6  | 
| movies | 0  | 3  | 2  | 6  | 1  | 
| history | 4  | 6  | 2  | 3  | 3  | 
|... 

我想计算和可视化它们的相关性。所以说我想看看有关的音乐和更类似于关于电影,或政体的文档等文件

在做:

csv <- read.csv("documents.csv") 
matrix <- data.matrix(csv) 
cor(matrix) 

我得到:

  topic  word1  word2  word3  word4  word5 
topic 1.00000000 0.08111071 -0.94812244 0.00000000 -0.6868028 0.3779645 
word1 0.08111071 1.00000000 0.21296184 0.62828086 -0.7687575 -0.1635038 
word2 -0.94812244 0.21296184 1.00000000 0.09415545 0.4307761 -0.3032248 
word3 0.00000000 0.62828086 0.09415545 1.00000000 -0.3546635 -0.8132501 
word4 -0.68680282 -0.76875749 0.43077610 -0.35466345 1.0000000 -0.2249755 
word5 0.37796447 -0.16350382 -0.30322482 -0.81325006 -0.2249755 1.0000000 

其实我不确定我是否得到了正确的结果以及如何解释它们。

更新:

> dput(csv) 
structure(list(topic = structure(c(4L, 5L, 3L, 2L, 1L), .Label = c("history", 
"movies", "music", "politics", "sports"), class = "factor"), 
    word1 = c(5L, 2L, 2L, 0L, 4L), word2 = c(2L, 0L, 3L, 3L, 
    6L), word3 = c(4L, 1L, 1L, 2L, 2L), word4 = c(0L, 1L, 3L, 
    6L, 3L), word5 = c(1, 6, 6, 1, 3)), .Names = c("topic", "word1", 
"word2", "word3", "word4", "word5"), class = "data.frame", row.names = c(NA, 
-5L)) 


> dput(matrix) 
structure(c(4, 5, 3, 2, 1, 5, 2, 2, 0, 4, 2, 0, 3, 3, 6, 4, 1, 
1, 2, 2, 0, 1, 3, 6, 3, 1, 6, 6, 1, 3), .Dim = 5:6, .Dimnames = list(
    NULL, c("topic", "word1", "word2", "word3", "word4", "word5" 
    ))) 

回答

1

你可能想要删除的转置矩阵的第一列和工作:

csv <- read.csv("documents.csv") 

row.names(csv) <- csv[,1] 

csv <- csv[,-1] 

matrix <- as.matrix(csv) 
cor(t(matrix)) 
+0

它说'错误心病(T(矩阵)):“ x'必须是数字的。 – user1170330

+0

我的代码更多的是一个例子,因为我没有你的数据集。如果没有更多的字符列,调用'numeric()'应该可以解决这个问题。 –

+0

问题中cor()的输出显示在相关矩阵中使用了字符'topic'。这显然不是理想的行为。因此,我把它“转移”给了流行歌曲。 –