#------------------ GENERATE SAMPLE DATA
rm(list=ls()) #clean
require(igraph) #random graphs
require(AER) #get ivreg ...
n<-700 #700 locations
p=0.2
g <- erdos.renyi.game(n=n, p.or.m=p, type="gnp", directed=F, loops=F)
graph.density(g)
w <- get.adjacency(g) #get an adjacency matrix
w <- w/rowSums(w) #row standardize because of eigen vectors and eigen values
sum(rowSums(w)==0)
rho <- 0.5
intercept <- rep(1,n)
rvariable <- runifrnorm(n)
y <- solve(diag(n) - rho*w) %*% ( 2*intercept + 3*rvariable + rnorm(n))
#------------------ GENERATE INSTRUMENTS
#get some instrumental variables
z0 <- w%*%rvariable
z1 <- w%*%w%*%rvariable
z2 <- w%*%w%*%w%*%rvariable
#check to see if there is a minimum of correlation ... it shoudl
cor(z0, w%*%y)
cor(z1, w%*%y)
cor(z2, w%*%y)
#------------------ NOW ONTO ESTIMATION
#The wrong way ...
summary(out<-lm(y ~ rvariable))
confint(out)
#The not so bad, but still very wrong way
summary(out<-lm(y ~ w%*%y + rvariable))
confint(out)
#ok now this should do it ... not perfect beacuse 2sls is not efficient.
#I am doing it this way because i did not want to generate random maps...
#Plus random graphs are easily available !
summary(out<-ivreg( y ~ w%*%y + rvariable, instruments=~ z0 + z1 + z2 + rvariable ))
confint(out)
In the end you should see the residuals difference == 0 !
A cautionary note here is that depending on the structure of w the effect might not be identifiable so the strategy of using the random graph generator might be bogus some times !
Anyway I hope this really solved your question