---
# System prepended metadata

title: Saptial Model
tags: [空間模型, Saptial Model, Econometrics, 計量經濟]

---

---
GA: UA-159972578-2
---

###### tags: `計量經濟` `Econometrics` `Saptial Model` `空間模型`

# Saptial Model

## 讀取資料
```{r}
# Read in the SHP file (Map + Data in one) using rgdal
library(rgdal)
spat.data = readOGR(dsn = ".", layer = "NCVACO")
options(scipen=7) # 將科學記號設在第幾位開始
```

## 使用相鄰矩陣(Adjacency Matrix)當作權重

`nb2listw`可以計算相鄰矩陣並存成list，matrix的row裡面都是一個county的index，所以可以知道相鄰的index是誰。
```{r}
# make weights matrix (nb type) 
library(spdep)
queen.nb = poly2nb(spat.data) 
rook.nb = poly2nb(spat.data,queen=FALSE) 
queen.listw = nb2listw(queen.nb) # convert nb to listw type
rook.listw = nb2listw(rook.nb)   # convert nb to listw type
```

## Statistic Test

### Moran Test on Residual
檢驗OLS可不可以用
+ Ho: Spatial Correlation Doesn't Exists 
+ Ha: Spatial Correlation Exists 
```{r}
lm.morantest(ols, weights=rook.listw)
```

```
	Global Moran I for regression residuals
data:  
model: lm(formula = reg.eq1, data = spat.data)
weights: listw1

Moran I statistic standard deviate = 5, p-value = 0.000002
alternative hypothesis: greater
sample estimates:
Observed Moran I      Expectation         Variance 
         0.19728         -0.01057          0.00205 
```
結果：p=0.000002196(拒絕假設，因此不能用OLS) => Spatial Correlation Exists 

### Lagrange Multiplier Test on the 1st Gradiant of Likelihood
與OSL相比，所有放進來的模型誰比較穩健，p值愈小愈好
```{r}
ols = lm(formula, data=spat.data)
lm.LMtests(ols, weights=rook.listw, test="all") 
```

### Hausman Test

+ Spatial Hausman Test
	+ 顯著:兩個都不能用
	+ 不顯著:可以用較OLS複雜的
+ Panel Data Hausman Test
	+ 顯著：用Fixed Effect
	+ 不顯著：用Random Effect
```{r}
Hausman.test(reg4)
```

## 模型介紹

### (SAR)

### Spatially Lagged X (SLX)
y=Xß+WXT+e

### (SDM)

### (SEM)

