darkage
darkage

Reputation: 857

Replacing for loop with apply fuctions

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

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))

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")
  }  
}

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

The code is looked up from R-bloggers website

Upvotes: 1

Views: 61

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388982

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")

For example,

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

Upvotes: 3

Related Questions