簡體   English   中英

用 apply 函數替換 for 循環

[英]Replacing for loop with apply fuctions

我想在 R 中用適當的 apply 函數替換嵌套的 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 循環,因為返回矩陣需要很長時間。

代碼是從R-bloggers網站上查到的

您可以在此處使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM