Search code examples
listfor-loopapplymap-functionspatstat

How I can select 2 variables from the list of data within mapply or Map functions in R?


I have a list of data frames from which 2 variables: utmX and utmY will be used for this analyze.

In the code below, I am trying to: 1) write L.fun() 2) apply this L.fun() to a list of data frames 3) plot result of each data frame separately.

L.fun <- function(x, y){
  window <- ripras(x, y)
  p.patt <- ppp(x, y, window=window)
  L <- Lest(p.patt, correction="Ripley")
  return(L)
}

 data.list <- list(data1,data2,data3...data30)

 L.res <- mapply(L.fun, data.list$utmX, data.list$utmY)  # empty
 L.res <- mapply(L.fun, x$utmX, x$utmY) # x object not found
 L.res <- Map(L.fun, data.list)         # arg y is missing 
 plot(L.res)

Also I tried this by including x and y inside of function, stil not working.

 L.res <- lapply(data.list, function(x) {
    for(i in 1:nrow(x)){
       window <- ripras(x$utmX, x$utmY)
       p.patt <- ppp(x$utmX, x$utmY, window=window)
       x$L <- Lest(p.patt, correction="Ripley")
   }
   x
 })

So my question is how I can select 2 variables that going to be used for mappy and Map functions from the list of data?

Thank you very much!


Solution

  • A slight modification of your second attempt should work.

    library(spatstat)
    

    First generate a list of 2 fake datasets:

    data.list <- replicate(2, data.frame(utmX=runif(20), utmY=runif(20)), simplify = FALSE)
    

    Run through the list and apply the L function to each dataset in the list:

    L.res <- lapply(data.list, function(x) {
      window <- ripras(x$utmX, x$utmY)
      p.patt <- ppp(x$utmX, x$utmY, window=window)
      return(Lest(p.patt, correction="Ripley"))
    })
    

    The result is a list of two L functions as shown in the plot:

    plot.anylist(L.res)
    

    Created on 2019-03-14 by the reprex package (v0.2.1)