专注系列化、高质量的R语言教程
推文索引 | 联系小编 | 付费合集
有读者不知道如何用地理加权回归去预测新的数据。本篇以常用的两个工具包为例进行介绍。
本篇目录如下:
0 数据准备
1 spgwr工具包
2 GWmodel工具包
3 结语
相关推文:
spgwr | R语言与地理加权回归(Ⅰ-1):线性地理加权回归
spgwr | R语言与地理加权回归(Ⅰ-2):广义线性地理加权回归
GWmodel | 地理加权模型(Ⅱ-1):地理加权主成分分析(GWPCA)
GWmodel | 地理加权模型(Ⅱ-2):如何查看地理加权回归的显著性
示例数据是来自spData
工具包的NY8_utm18.shp
。该数据在推文线性地理加权回归中使用过。
library(rgdal)
NY8 <- readOGR(system.file("shapes/NY8_utm18.shp",package = "spData"))
该数据共包含281个空间单元。随机选择其中的276个作为模型数据,剩余5个作为预测数据。代码如下:
set.seed(0312)
modelid <- sample(1:281, 276)
predid <- setdiff(1:281, modelid)modeldata <- NY8[modelid,]
preddata <- NY8[predid,]plot(modeldata)
plot(preddata, add = T, col = "red")
使用spgwr
工具包的函数运行一个地理加权模型:
library(spgwr)
form <- Z ~ PEXPOSURE + PCTAGE65P + PCTOWNHOME
bw <- gwr.sel(formula = form, data = modeldata,gweight = gwr.Gauss, method = "cv")model <- gwr(formula = form, data = modeldata,bandwidth = bw, gweight = gwr.Gauss)
该模型不能使用predict()
函数进行预测:
predict(model, preddata)
## Error in UseMethod("predict") :
## no applicable method for 'predict' applied to an object of class "gwr"
在R语言中,使用什么函数预测模型需要看对应工具包的设计。比如spgwr
工具包,在帮助文档中可以发现gwr()
函数有两个参数与模型预测有关:
fit.points
: an object containing the coordinates of fit points; often an object from package sp; if missing, the coordinates given through the data argument object, or the coords argument are used;
predictions
: default FALSE; if TRUE and no fit points given, return GW fitted values at data points, if fit points given and are a Spatial*DataFrame object containing the RHS variables in the formula, return GW predictions at the fit points.
因此,在spgwr
工具包中模型运行和预测使用的是同一个函数;如需使用新数据进行预测,需使用fit.points
参数指定包含新数据的矢量数据,并设置predictions = TRUE
。
model12 <- gwr(formula = form, data = modeldata,bandwidth = bw, gweight = gwr.Gauss,fit.points = preddata,predictions = T)
## 查看预测结果
model12$SDF$pred
## [1] 0.04586992 -0.36963028 -0.09173360 -0.39631776 0.13528131
对比
model
和model12
的SDF
可以发现:不需要模型预测的model
,其SDF@data
对应的是模型数据;需要模型预测的model12
,其SDF@data
对应的是预测数据;其他函数如
ggwr()
函数的预测方法类似。
使用GWmodel
工具包的函数运行一个地理加权模型(带宽参数bw
仍使用上例的值):
library(GWmodel)
model2 <- gwr.basic(formula = form, data = modeldata,bw = bw, kernel = "gaussian")
该工具包同样不支持使用predict()
函数进行模型预测:
predict(model2, preddata)
## Error in UseMethod("predict") :
## no applicable method for 'predict' applied to an object of class "gwrm"
查看帮助文档可发现一个gwr.predict()
函数,其参数predictdata
的说明如下:
predictdata
: a Spatial*DataFrame object to provide prediction locations, i.e. SpatialPointsDataFrame or SpatialPolygonsDataFrame as defined in package sp.
示例如下:
model22 <- gwr.predict(formula = form, data = modeldata,bw = bw, kernel = "gaussian",predictdata = preddata)
## 查看预测结果
model22$SDF$prediction
## [1] 0.04586992 -0.36963028 -0.09173360 -0.39631776 0.13528131
关于R语言中的函数使用方法,学堂君在下面的推文中已经介绍了:
如何正确使用R语言的函数——为什么有的模型结果不能使用summary函数查询?