Skip to content

how to fit corSpher with gls?

2 messages · Andy Bunn

#
Ugh! Forgot to specify the form of the object. Fixed below.
On 5/18/15, 12:57 PM, "Andy Bunn" <Andy.Bunn at wwu.edu> wrote:

            
# Refit a model with an approparite correlation structure.
# Corr structure with range and nugget from above and specifying
# the form
cs1 <- corSpher(c(17,0.3),form=~easting+northing,nugget=TRUE)
gls1 <- gls(y~x,data=dat,correlation=cs1)
summary(gls1)
# add the residuals to the spatial dat object
dat$glsResids <- residuals(gls2,type="normalized")
# Moran's I test comes back clean
moran.test(dat$glsResids, nb2listw(w))
#
One more typo. Here is the complete script:

library(gstat)
library(sp)
library(nlme)
library(spdep)
library(ncf)



set.seed(234)
# generate the spatially autocorrelated error term, epsilon
n <- 200
epsilon <- rnorm(n,0,1)

easting <- runif(n,0,100)
northing <- runif(n,0,100)
points <- cbind(easting,northing)
dnb <- dnearneigh(points, 0, 150)
dsts <- nbdists(dnb, points)
idw <- lapply(dsts, function(x) 1/x^1.5) # p=1.5
lw <- nb2listw(dnb, glist=idw, style="W")

rho <- 0.95
inv <- invIrW(lw, rho)

epsilon <- inv %*% epsilon
epsilon <- scale(epsilon[,1])


# generate x as noise.
x <- rnorm(n)
# generate y as a function of x and epsilon (which is spatially
autocorrelated)
B0 <- 10
B1 <- 2
y <- B0 + B1*x + epsilon

# Create a spatial object
dat <- data.frame(easting,northing,y,x)
coordinates(dat)<-c('easting','northing')

# Fit a model (we don't know about spatial component)
lm1 <- lm(y~x, dat)
coefficients(summary(lm1))

# Add residuals to the SPDF dat
dat$lmResids <- residuals(lm1)

# Map the rediduals
bubble(dat, zcol = 'lmResids')

# Test them for spatial autocorrelation using moran.test,
# a correlogram and a variogram.

# Moran's I test
w <- knn2nb(knearneigh(dat, k=8))
moran.test(dat$lmResids, nb2listw(w))

# Moran's I correlogram
residsI <- spline.correlog(x=coordinates(dat)[,1], y=coordinates(dat)[,2],
                         z=dat$lmResids, resamp=20)
plot(residsI)

# Variogram
lmResidsVar <- variogram(lmResids~1, data=dat)
plot(lmResidsVar)
sph.model <- vgm(psill=1, model="Sph", range=20, nugget=0.3)
sph.fit <- fit.variogram(object = lmResidsVar, model = sph.model)
plot(lmResidsVar,model=sph.fit)

# Refit a model with an approparite correlation structure.
# Corr structure with range and nugget from above and specifying
# the form
cs1 <- corSpher(c(17,0.3),form=~easting+northing,nugget=TRUE)
gls1 <- gls(y~x,data=dat,correlation=cs1)

summary(gls1)

# add the residuals to the spatial dat object
dat$glsResids <- residuals(gls1,type="normalized")

# Map the rediduals from gls
bubble(dat, zcol = 'glsResids')

# Moran's I test
moran.test(dat$glsResids, nb2listw(w))
# Moran's I correlogram
residsI <- spline.correlog(x=coordinates(dat)[,1], y=coordinates(dat)[,2],
                         z=dat$glsResids, resamp=20)
plot(residsI)
On 5/18/15, 3:03 PM, "Andy Bunn" <Andy.Bunn at wwu.edu> wrote: