我正在运行一个R程序,该程序计算产品说明之间的相似性。程序的输入是一个具有1列的文件,其中包含产品说明列表,每个产品说明都位于单独的行上
我还有一个包含产品标题列表的文件,每个文件都在单独的行上。
使用dist函数,我计算了产品说明之间的相似度,并将它们存储在dist.mat中作为矩阵。
接下来,我想将产品标题加入到我计算出的相似度中。因此,我阅读了名称中的产品标题,然后:
dist.mat <- data.frame(dist.mat, row.names=Names[,1])
colnames(dist.mat) <- (row.names(dist.mat))
然后我得到一个错误:data.frame(dist.mat,row.names = Names [,1])中的错误:提供的行名长度错误
不确定如何解决它。我读到此:'row.names'长度无效,但我无法使用Sample $或as.character修复错误
我正在使用:lsa_0.73,SnowballC_0.5.1,tm_0.5-10
这是一个实际示例:Product Desc文件:
产品标题文件:
如果有人可以帮忙会很棒
dist
向量的距离矩阵(类别)显示为比向量长度小的三角形矩阵一行和一列。
library(stringdist)
desc <- c("This glass can be used to drink whiskey",
"This is a stainless steel glass",
"This is a red rose")
Names <- c("Whiskeyglass", "glass", "rose")
dist.mat1 <- stringdistmatrix(desc)
dist.mat1
# 1 2
# 2 27
# 3 24 18
但是,dist
对象没有尺寸,因此无法为它分配行名和列名。
dim(dist.mat1)
# NULL
尝试命名dist
对象的行和列会导致错误。
row.names(dist.mat1) <- colnames(dist.mat1) <- Names
as.data.frame.default(x [[i]],可选= TRUE)中的错误:无法将类““ dist”“强制转换为data.frame
为了获得您期望的结果,dist
首先需要将一个对象转换为matrix
。沿对角线将零相加,因此也将行和列相加。
if(class(dist.mat1) == "dist"){
dist.mat2 <- as.matrix(dist.mat1)
row.names(dist.mat2) <- colnames(dist.mat2) <- Names
} else {
dist.mat2 <- dist.mat1
row.names(dist.mat2) <- colnames(dist.mat2) <- Names
}
dist.mat2
# Whiskeyglass glass rose
# Whiskeyglass 0 27 24
# glass 27 0 18
# rose 24 18 0
如果您的dist.mat
外观dist.mat1
如上,但其类别为matrix
,则您需要选择哪些名称所属。
row.names(dist.mat) <- Names[-1] # removing the first name for rows
colnames(dist.mat) <- Names[-length(Names)] # removing the last name for columns
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句