我是空间统计学的新手,我正在尝试为R中美国所有人口普查区域创建一个空间权重矩阵。大约有74000个区域。
基于美国人口普查老虎文件,我创建了所有区域的shapefile,然后(使用spdep包):
#Create adjacency matrix
am = poly2nb(us)
is.symmetric.nb(am)虽然am很大,但它工作得很好。
接下来:
am = nb2mat(am, style="B",zero.policy=T)这就给了我这个错误:
Error: cannot allocate vector of size 40.9 Gb显然,我的笔记本电脑不能处理40.9 Gb的内存。我试过在亚马逊网络服务的EC2云上这样做,但是为了获得这么大的内存,我需要得到一个非常大的实例,因为我是云计算的新手,我宁愿在免费的T2.micro沙盒(最大1 GiB内存)中玩,直到我准备花一些钱在更大的机器上。如果我能把权重矩阵变成稀疏矩阵,我想我就能处理它,但我不知道怎么做。我试着这样做:
Wmat<-Matrix(nb2mat(am, style="B",zero.policy=T),sparse=TRUE)但在创建稀疏矩阵之前,它仍然需要所有内存来执行nb2mat命令。
有什么解决方案吗?
发布于 2015-07-07 02:48:06
当然有点晚了。但我想我想出了一个解决方案。我的71k*71k矩阵也有类似的情况。
我刚刚修改了nb2mat函数,以便使用bigmemory库中的big.matrix。我们需要定义两个新函数:
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
}
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函数:
a=my_nb2mat(neighbours = out, style='W',zero.policy =F )注意: bigmemory库似乎只在R\R-2.15.3中对我有效。
https://stackoverflow.com/questions/28989325
复制相似问题