library(pspatreg)
###############################################
# Examples using spatial data of Ames Houses.
###############################################
# Getting and preparing the data
library(spdep)
library(sf)
ames <- AmesHousing::make_ames() # Raw Ames Housing Data
ames_sf <- st_as_sf(ames, coords = c("Longitude", "Latitude"))
ames_sf$Longitude <- ames$Longitude
ames_sf$Latitude <- ames$Latitude
ames_sf$lnSale_Price <- log(ames_sf$Sale_Price)
ames_sf$lnLot_Area <- log(ames_sf$Lot_Area)
ames_sf$lnTotal_Bsmt_SF <- log(ames_sf$Total_Bsmt_SF+1)
ames_sf$lnGr_Liv_Area <- log(ames_sf$Gr_Liv_Area)
ames_sf1 <- ames_sf[(duplicated(ames_sf$Longitude) == FALSE), ]
#### GAM pure with pspatreg
form1 <- lnSale_Price ~ Fireplaces + Garage_Cars +
pspl(lnLot_Area, nknots = 20) +
pspl(lnTotal_Bsmt_SF, nknots = 20) +
pspl(lnGr_Liv_Area, nknots = 20)
gampure <- pspatfit(form1, data = ames_sf1)
summary(gampure)
# \donttest{
#' ########### Constructing the spatial weights matrix
coord_sf1 <- cbind(ames_sf1$Longitude, ames_sf1$Latitude)
k5nb <- knn2nb(knearneigh(coord_sf1, k = 5,
longlat = TRUE, use_kd_tree = FALSE), sym = TRUE)
lw_ames <- nb2listw(k5nb, style = "W",
zero.policy = FALSE)
##################### GAM + SAR Model
gamsar <- pspatfit(form1, data = ames_sf1,
type = "sar", listw = lw_ames,
method = "Chebyshev")
summary(gamsar)
### Compare Models
anova(gampure, gamsar, lrtest = FALSE)
## logLikelihood
logLik(gamsar)
## Restricted logLikelihood
logLik(gamsar, REML = TRUE)
## Parametric and spatial coefficients
print(gamsar)
coef(gamsar)
## Frequentist (sandwich) covariance matrix
## (parametric terms)
vcov(gamsar, bayesian = FALSE)
## Bayesian covariance matrix (parametric terms)
vcov(gamsar)
#####################################
#### Fitted Values and Residuals
plot(gamsar$fitted.values,
ames_sf1$lnSale_Price,
xlab = 'fitted values',
ylab = "unrate",
type = "p", cex.lab = 1.3,
cex.main = 1.3,
main = "Fitted Values gamsar model")
plot(gamsar$fitted.values, gamsar$residuals,
xlab = 'fitted values', ylab = "residuals",
type = "p", cex.lab = 1.3, cex.main=1.3,
main = "Residuals geospsar model")
# }
Run the code above in your browser using DataLab