R 矩阵相关性的计算

R 矩阵相关性的计算,r,csv,matrix,correlation,similarity,R,Csv,Matrix,Correlation,Similarity,我有一个矩阵,里面有一些文件和所有的单词。数字表示该单词在文档中出现的次数 | topic | word1 | word2 | word3 | word4 | word5 |... |----------|-------|-------|-------|-------|-------| | politics | 5 | 2 | 4 | 0 | 1 | | sports | 2 | 0 | 1 | 1 | 6

我有一个矩阵,里面有一些文件和所有的单词。数字表示该单词在文档中出现的次数

| 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)
事实上,我不确定我是否得到了正确的结果以及如何解释它们

更新:

> 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"
    )))

您可能希望删除第一列并处理转置矩阵:

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

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

csv <- csv[,-1]

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

csv它在cor(t(矩阵))中表示
错误:'x'必须是数字
。我的代码更像是一个示例,因为我没有您的数据集。如果没有更多的字符列,则调用
numeric()
可以解决此问题。问题中cor()的输出显示相关矩阵中使用了字符“topic”。这显然不是理想的行为。因此,我将其“转移”到行名中。@DavidH:我的数据集具有示例中提供的结构。我必须在哪里应用数值?当我做
cor(t(as.numeric(matrix))
时,它说
(list)对象不能强制输入'double'
。这可能意味着你的
矩阵实际上仍然是一个data.frame。您可能希望尝试将
作为.matrix()
。如果没有自己的数据,很难帮助您,请使用
dput()
发布您的数据。
csv <- read.csv("documents.csv")

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

csv <- csv[,-1]

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