在R中找到余弦相似度

时间:2018-08-05 10:00:38

标签: r similarity cosine-similarity

我有两个csv文件,在这两个文件的第一列中,字符最多可以运行50000个变量。我必须计算两个文件的这些列之间的余弦相似度。我试图在R中使用LSA。但是我的结果有些问题。谁能帮我?下面是我的编码。

library(lsa)
Gyan=tempfile() 
dir.create(Gyan) 
single_tags=read.csv(file.choose(), sep = ',')
as.character(single_tags$CULTAGS) 
options(max.print = 1000000) 
write(as.character(single_tags$CULTAGS),file = paste(Gyan, 'D1',sep = '1')) 
Single_ASFA=read.csv(file.choose(),sep = ',')
options(max.print = 1000000) 
as.character(Single_ASFA$ASFACV)
write(as.character(Single_ASFA$ASFCV),file = paste(Gyan, '/')) 
Mycomparison = textmatrix(Gyan, minWordLength = 1)
Mycomparison
res = lsa::cosine(myMatrix[,1],myMatrix[,2]) 
res 

1 个答案:

答案 0 :(得分:0)

似乎与myMatrixMycomparison没有关系。如果将MyMatrix替换为Mycomparison,一切正常。如下所示:

# Data Simulation
single_tags_df <- data.frame( CULTAGS =  c("dog", "cat", "sushi", "mouse", "leech"))
Single_ASFA_df <- data.frame(ASFCV =  c("hamster", "mouse", "sushi", "man"))
write.csv(single_tags_df, file = "single.csv")
write.csv(Single_ASFA_df, file = "ASFA.csv")

library(lsa)
Gyan <- tempfile() 
dir.create(Gyan) 

single_tags <- read.csv("single.csv", sep = ",")
as.character(single_tags$CULTAGS) 
options(max.print = 1000000) 
write(as.character(single_tags$CULTAGS), file = paste(Gyan, "D1", sep = "/")) 
Single_ASFA <- read.csv("ASFA.csv", sep = ",")
options(max.print = 1000000) 
as.character(Single_ASFA$ASFCV)
write(as.character(Single_ASFA$ASFCV), file = paste(Gyan, "D2", sep = "/")) 

Mycomparison <- textmatrix(Gyan)
Mycomparison
unlink(Gyan)

res <- lsa::cosine(Mycomparison[, 1], Mycomparison[, 2]) 
res 
#           [,1]
# [1,] 0.4472136