rlapplyspdep

R error with spatial point data frame when using lapply


I have a list of lists called flat_head.

dput(flat_head)
structure(list(`0.25_0.05` = list(c(66, 102, 4.84), c(56, 75, 
3.63), c(15, 134, 0)), `0.25_0.1` = list(c(147, 27, 0), c(98, 
18, 4.84), c(141, 54, 4.84)), `0.5_0.05` = list(c(64, 130, 4.84
), c(61, 97, 4.84), c(58, 16, 4.84))), .Names = c("0.25_0.05", 
"0.25_0.1", "0.5_0.05"))

I wrote a small function to run through each list and calculate Moran's I from a spatial points data frame. It works for a single list but it throws an error when I use lapply.

require(spdep)
M_fun <-  function(x){
  x2 <- unlist(x[[1]])
  x3 <- matrix(x2,ncol = 3, byrow=TRUE)
  colnames(x3) <- c("x","y","prey")
  coords1<-as.data.frame(x3[,1:2])
  spdf <- SpatialPointsDataFrame(coords1,as.data.frame(x3[,3]))
  nm <- knn2nb(knearneigh(spdf))
  all.linked <- max(unlist(nbdists(nm, spdf)))
  nb <- dnearneigh(spdf, 0, all.linked)
  colW <- nb2listw(nb, style="W")
  results1<-moran(spdf@data$`x3[, 3]`, colW, length(nb), Szero(colW))
  return(results1)
}
y<- M_fun(flat_head) # works
final<-lapply(flat_head, M_fun) # does not work

Any suggestions on what I'm doing wrong?


Solution

  • y<- M_fun(flat_head) # works final<-lapply(flat_head, M_fun) # does not work

    For these two to be equivalent you would have to have y <- M_fun(flat_head[[1]]) or similar since lapply() applies the function to each element of the list.

    At the moment my guess is that y<- M_fun(flat_head) is giving you the output of M_fun for just the first list of flat_head. This is because you have x2 <- unlist(x[[1]]) in the first line of the function.

    If you change this to x2 <- unlist(x) it should work.

    Consider using dput(flat_head) to create a better reproducible example.