使用lapply时,空间点数据帧出现R错误

时间:2017-12-07 15:09:14

标签: r lapply spdep

我有一个名为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"))

我编写了一个小函数来遍历每个列表,并从空间点数据框计算出Moran的I。它适用于单个列表,但在使用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

关于我做错了什么的任何建议?

1 个答案:

答案 0 :(得分:1)

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

由于y <- M_fun(flat_head[[1]])将函数应用于列表的每个元素,因此要使这两者具有等效性,您必须具有lapply()或类似内容。

目前我的猜测是y<- M_fun(flat_head)只为第一个flat_head列表提供了M_fun的输出。这是因为你在函数的第一行有x2 <- unlist(x[[1]])

如果将其更改为x2 <- unlist(x)则应该有效。

考虑使用dput(flat_head)创建更好的可重现示例。