Home > OS >  How to optimize script using loops in R
How to optimize script using loops in R

Time:12-29

I've defined a distance matrix to be used for moran index calculation. As I want to use multiple cutoff distances to analyze the impact of different weights specification on Moran results, I proceed as follows:

    md # the distance matrix
    #define cutoff
    md_05 <- md
    md_10 <- md
    md_15 <- md
    md_20 <- md
    md_25 <- md
    md_30 <- md
    md_35 <- md
    md_40 <- md
    #distance inverse matrix calculation 5 km
    md_05[md_05>5] <- 0
    md_05[md_05 == 0] <- NA
    md_05 <- md_05 [,-1]
    m_dist_05 <- as.matrix(md_05)
    mdi_05 <- 1/m_dist_05 
    diag(mdi_05) <- 0
    mdi_05[is.na(mdi_05)] = 0
    ### Definition of the spatial weight matrix
    listw_05 <- mat2listw(mdi_05, row.names = row.names(mdi_05), style = "W")

I just reported the code I used for one cutoff distance (5km) but as I have to repeat the same procedure for other distances (10, 15, 20, and so on), I was just wondering if there is a way to optimize the code avoiding to copy and past it, as many times as the distances I need to calculate. I'm not familiar at all with loops (I know I should start to learn them), but I'm quite sure the problem could simply be solved using something like that. Any suggestions or feedback about how to find a solution for my problem would be appreciate, thanks

CodePudding user response:

Write a function with those calculations, define a cutoffs vector and lapply the function to this vector. Untested, since there are no data.

makemat <- function(cutoff, m) {
  m[m > cutoff] <- 0
  m[m == 0] <- NA
  m <- m[,-1]
  m_dist <- as.matrix(m)
  mdi <- 1/m_dist
  diag(mdi) <- 0
  mdi[is.na(mdi)] = 0
  ### Definition of the spatial weight matrix
  mat2listw(mdi, row.names = row.names(mdi), style = "W")
}

cutoff_vec <- seq(5L, 40L, by = 5L)
results_list <- lapply(cutoff_vec, makemat, m = md)
  •  Tags:  
  • r
  • Related