用 apply 函数替换 for 循环

Replacing for loop with apply fuctions

我想用 R 中的适当应用函数替换嵌套的 for 循环。

我声明了一个具有以下维度的矩阵 - ncol 是 412,nrow 是 2164

dist.name.enh <- matrix(NA, ncol = length(WW_name),nrow = length(Px_name))

计算字符串距离的for循环如下

for(i in 1:length(WW_name)) {
  for(j in 1:length(Px_name)) {

    dist.name.enh[j,i]<-stringdist(tolower(WW_name)[i],
                                   tolower(Px_name)[j],
                                   method = "lv")
  }  
}

如何避免 for 循环,因为 return 矩阵需要很长时间。

代码来自R-bloggers website

您可以在此处使用 outer,这会将函数应用于 xy 的每个组合。

outer(tolower(WW_name), tolower(Px_name), stringdist::stringdist, method = "lv")

例如,

x <- c("random", "strings", "to", "test")
y <- c("another", "string", "test")

outer(x, y, stringdist::stringdist, method = "lv")

#      [,1] [,2] [,3]
#[1,]    6    6    6
#[2,]    7    1    6
#[3,]    6    5    3
#[4,]    6    5    0