我正在尝试使用包 CARBayes 进行区域单元分析。作为分析的一部分,我使用以下代码。当我尝试使用nb2mat
. 我的 sp 对象中有 170,000 个奇数多边形,因此它无法用我拥有的内存制作矩阵。
library(spdep)
library(CARBayes)
W.nb <- poly2nb(sp)
W <- nb2mat(W.nb, style = "B", zero.policy = TRUE)
test <- S.CARbym(case ~ covariate1),
family = "poisson",
data = sp,
W = W,
burnin = 10000,
n.sample = 30000,
thin = 20)
我在另一个线程中找到了以下代码来制作bigmemory
矩阵,但 CARBayes 不会将其识别为矩阵。
我的问题是,有没有人知道使用/sparse 矩阵bigmemory
或spam
类似的东西来创建矩阵的方法,以便可以在 CARBayes 包中使用它而不会抛出错误,说它W
不是矩阵。
my_listw2mat = function (listw)
{
require(bigmemory)
n <- length(listw$neighbours)
if (n < 1)
stop("non-positive number of entities")
cardnb <- card(listw$neighbours)
if (any(is.na(unlist(listw$weights))))
stop("NAs in general weights list")
#res <- matrix(0, nrow = n, ncol = n)
res <- big.matrix(n, n, type='double', init=NULL)
options(bigmemory.allow.dimnames=TRUE)
for (i in 1:n) if (cardnb[i] > 0)
res[i, listw$neighbours[[i]]] <- listw$weights[[i]]
if (!is.null(attr(listw, "region.id")))
row.names(res) <- attr(listw, "region.id")
res
}
my_nb2mat = function (neighbours, glist = NULL, style = "W", zero.policy = NULL)
{
if (is.null(zero.policy))
zero.policy <- get("zeroPolicy", envir = .spdepOptions)
stopifnot(is.logical(zero.policy))
if (!inherits(neighbours, "nb"))
stop("Not a neighbours list")
listw <- nb2listw(neighbours, glist = glist, style = style,
zero.policy = zero.policy)
res <- my_listw2mat(listw)
attr(res, "call") <- match.call()
res
}
W <- my_nb2mat(W.nb, style = "B", zero.policy = TRUE)
test <- S.CARbym(case ~ covariate1),
family = "poisson",
data = sp,
W = W,
burnin = 10000,
n.sample = 30000,
thin = 20)