2016-02-29 149 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'。這顯然不是理想的行爲。因此,我把它「轉移」給了流行歌曲。 –