0

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

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

3 Comments

That's a great and simple solution, thanks Rui, I tried it on my data and it works fine. Just a thing, is there a way to store in different objects the results for each distance? As lapply stores all spatial weight matrices in one object (results_list) but I need it to be separate
@Ramon_88 I suggest that you keep the several objects in one place, one list but if you want to have them all in the .GlobalEnv, start by naming the list, say, names(results_list) <- sprintf("listw_%02d", cutoff_vec) followed by list2env(results_list, envir = .GlobalEnv).
This is exactly what I wanted, thanks again @Rui Barradas!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.