Skip to content

Instantly share code, notes, and snippets.

@Framartin
Created September 19, 2015 21:09
Show Gist options
  • Save Framartin/a8cc1fc1c2aec2c0faad to your computer and use it in GitHub Desktop.
Save Framartin/a8cc1fc1c2aec2c0faad to your computer and use it in GitHub Desktop.
Code used to compute lagged variables in predict.sarlm()
K <- ifelse(colnames(X)[1] == "(Intercept)", 2, 1)
m <- ncol(X)
# check if there are enough regressors
if (m > 1) {
WX <- matrix(nrow=nrow(X),ncol=(m-(K-1)))
for (k in K:m) {
wx <- lag.listw(listw, X[,k],
zero.policy=zero.policy)
if (any(is.na(wx)))
stop("NAs in lagged independent variable")
WX[,(k-(K-1))] <- wx
}
}
if (K == 2) {
# unnormalized weight matrices
if (!(listw$style == "W")) {
intercept <- as.double(rep(1, nrow(X)))
wx <- lag.listw(listw, intercept,
zero.policy = zero.policy)
if (m > 1) {
WX <- cbind(wx, WX)
} else {
WX <- matrix(wx, nrow = nrow(X), ncol = 1)
}
}
}
if (any(object$aliased)) {
if (K>1 && (listw$style == "W")) colnames(WX) <- paste("lag.", colnames(X)[-1], sep="")
else colnames(WX) <- paste("lag.", colnames(X), sep="")
WX <- WX[,!colnames(WX) %in% names(object$aliased[object$aliased])]
}
if (legacy.mixed) Xo <- cbind(Xo, WX)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment