使用应用功能替换循环 [英] Replacing for loop with apply fuctions

查看:64
本文介绍了使用应用功能替换循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to replace nested for loops with appropriate apply function in R.

我声明一个具有以下尺寸的矩阵-ncol为412,nrow为2164

I declare a matrix with the following dimensions - ncol is 412 and nrow 2164

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

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

The for loops for calculating the string distances are as below

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循环,因为返回矩阵会花费很长时间.

How do I avoid the for loops as it is taking very long to return the matrix.

R-bloggers网站

推荐答案

您可以在此处使用外部,该功能会将函数应用于 x 的每种组合y .

You can use outer here which will apply the function to every combination of x and y.

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

这篇关于使用应用功能替换循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆