使用 lapply 时空间点数据框出现 R 错误
R error with spatial point data frame when using lapply
我有一个名为 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's 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
对我做错了什么有什么建议吗?
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)
创建一个更好的可重现示例。
我有一个名为 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's 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
对我做错了什么有什么建议吗?
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)
创建一个更好的可重现示例。