R 使用mapply计算行名和列名之间的levenshteinDist
我想使用mapply函数计算矩阵的行名和列名之间的levenshteinDist距离:因为may矩阵的体积太大,使用嵌套循环“for”需要很长时间才能给出结果 下面是嵌套循环的旧代码:R 使用mapply计算行名和列名之间的levenshteinDist,r,matrix,levenshtein-distance,mapply,R,Matrix,Levenshtein Distance,Mapply,我想使用mapply函数计算矩阵的行名和列名之间的levenshteinDist距离:因为may矩阵的体积太大,使用嵌套循环“for”需要很长时间才能给出结果 下面是嵌套循环的旧代码: mymatrix <- matrix(NA, nrow=ncol(dataframe),ncol=ncol(dataframe),dimnames=list(colnames(dataframe),colnames(dataframe))) distfunction = function (text1,
mymatrix <- matrix(NA, nrow=ncol(dataframe),ncol=ncol(dataframe),dimnames=list(colnames(dataframe),colnames(dataframe)))
distfunction = function (text1, text2) {return(1 - (levenshteinDist(text1, text2)/max(nchar(text1), nchar(text2))))}
for(i in 1:ncol(mymatrix))
{
for(j in 1:nrow(mymatrix))
mymatrix[i,j]=(distfunction(rownames(mymatrix)[i], colnames(mymatrix)[j]))*100
}
它给了我这个错误:
Error in typeof(str2) : argument "text2" is missing, with no default
我计划将levenshteinDist距离应用于我的矩阵,然后总结如何应用myfunction
可能吗
谢谢。此上下文中不能使用函数
mapply
。它需要两个输入向量,函数应用于第一个元素,第二个元素。。等等但你希望所有的组合都适用
您可以尝试堆叠的sapply
sapply(colnames(mymatrix), function(col)
sapply(rownames(mymatrix), function(row)
distfunction(row, col)))*100
简单用法示例
输出:
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 2 4 6
[3,] 3 6 9
[4,] 4 8 12
更新
更好的方法是使用outer
,但我认为您的distfunction
没有矢量化(由于max
)。因此,请使用包装函数矢量化:
distfunction_vec <- Vectorize(distfunction)
outer(rownames(mymatrix), rownames(mymatrix), distfunction_vec)
distfunction\u vec谢谢@DeltaKappa。我试试这个解决办法。希望这能缩短执行时间。你的解决方案对我的脚本非常有效!非常感谢您@DeltaKappa。你真是个天才。我在尝试你的解决方案“更新”,希望能缩短执行时间。但我的函数似乎无法矢量化:我通过pmax
切换了max
,运行了distfunction\u vecVectorize
只在函数周围创建了一个薄薄的包装,所以对于矢量化函数,is.vector()
不会返回TRUE
。它只是更好地阅读与外部。我没想到会有绩效提升。
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 2 4 6
[3,] 3 6 9
[4,] 4 8 12
distfunction_vec <- Vectorize(distfunction)
outer(rownames(mymatrix), rownames(mymatrix), distfunction_vec)