我正在使用 R 包spdep,我想将两个listw
单独创建的对象合并为一个listw
。我不确定如何实现这一目标。我没有找到任何本机函数来做到这一点,如果我尝试将它们转换为权重矩阵,加入它们,然后重新转换回listw
我得到一个我无法解决的zero.policy错误,因为这应该在邻居时指定初始化。
重要的是,我需要将listw
它们分开,因为它们是另一个分析的一部分,这是必需的。
示例代码
library(sp)
library(spdep)
A <- SpatialPoints(data.frame(x = rnorm(10, -10),
y = rnorm(10, -10)))
B <- SpatialPoints(data.frame(x = rnorm(10, 10),
y = rnorm(10, 10)))
# neighbors
knn.A <- knn2nb(knearneigh(A))
knn.B <- knn2nb(knearneigh(B))
# listw
listw.A <- nb2listw(knn.A)
listw.B <- nb2listw(knn.B)
# and from here, how to join listw.A and listw.B ?
# stupid things I tried ------------------
rbind(listw.A, listw.B) #nope
# convert to matrix and back to listw
listw_mat <- list(listw.A, listw.B)
dims <- sapply(listw_mat, function(x) (dim(listw2mat(x)))[1])
mat <- matrix(0, nrow = sum(dims), ncol = sum(dims))
for (i in 1:length(dims)) {
start_col <- ifelse(i == 1, 1, dims[i - 1] + 1)
end_col <- ifelse(i == 1, dims[i], dims[i - 1] + dims[i])
mat[, start_col:end_col] <- listw2mat(listw_mat[[i]])
}
listw_mat <- mat2listw(mat, style = "S")
# the last prints a warning:
# Warning message:
# In nb2listw(res$neighbours, glist = res$weights, style = style, :
# zero sum general weights
# calling listw_mat prints the error:
# Error in print.listw(x) :
# regions with no neighbours found, use zero.policy=TRUE