Excercise: Click_here
##############################################################
# Exercise 5: Fixed effects and GAM
##############################################################
##############################################################
# Clear workspace and load needed packages
##############################################################
rm(list=ls())
# sometimes you need to define the loaction of the libraries
.libPaths("C:/Users/nhq455/Dropbox/R_packges")
.libPaths()
pack<-c("sandwich","lmtest","mgcv","foreign","AER","ggplot2","ggmap", "Hmisc","plm") #Create a list of package names
#
# for (i in pack){ #install packeages in the list pack
# install.packages(pkgs=i, dependencies=TRUE)
# }
lapply(pack, require, character.only=T) #loads the packages
#Define paths
data <-"C:/Users/nhq455/Dropbox/postdoc/course/PHD_course/PHD_spatial_econometrics_2017/PHD_course_2017/exercise/GIS_data"
results <-"E:/Dropbox/postdoc/course/PhD_course_2015/exercise/exercise_5"
##############################################################
# Load data
##############################################################
setwd(data)
getwd()
load("Ex_data.RData")
#List the objects in the workspace
ls()
#List the variables in the data set and check dimensions
ls(data.set)
dim(data.set)
#Create logs of some variables...
data.set$larea <- log(data.set$area)
data.set$lprice <- log(data.set$price)
##############################################################
# Define model
##############################################################
form<- formula(lprice ~ larea + rebuild_after + cpark + cscraplands +factor(date_year))
##############################################################
# OLS - no fixed effects or other spatial controls
##############################################################
lm.simple <- lm(form, data=data.set) #OLS model using formula "form" and data "data.set"
summary(lm.simple) # Summarize results - NB! the S.E.s assume no serial correlation
##############################################################
# Fixed effects models
##############################################################
#Create an ID variable
data.set$nr <- 1:length(data.set[,1])
setwd(results)
#Postal code areas
##Stores the results in the wd (Commented out here) - this is the R equivalent of a log file
#zz <- file("post.txt", open="wt")
#sink(zz)
#sink(zz, type="message")
# Postal code area information
length(unique(data.set$post_number)) #How many clusters?
min(table(data.set$post_number)) #How many units in the smallest cluster?
max(table(data.set$post_number)) #How many units in the largest cluster?
median(table(data.set$post_number)) #Median number of units within a cluster?
##############################################################
#Create the panel data set
##############################################################
data.post <-pdata.frame(data.set, index=c("post_number","nr"))
#Calculate some standard deviations within and between groups
vars <- c("larea", "lprice", "cpark", "cscraplands")
for(i in vars){
name <- paste("post.m",i, sep="")
assign(name,between(data.post[,i]))#Calculates group means of the variables in vars
}
for(i in vars){
name <- paste("post.w",i, sep="")
assign(name,Within(data.post[,i]))#Calculates deviation from group means of the variables in vars
}
M <- length(unique(data.set$post_number)) #How many clusters are there?
MT <- length(data.set$post_number) #How many obs in total?
#Between standard deviation
s.b.scrap <- (sum((post.mcscraplands-mean(data.post$cscraplands))^2)/(M-1))^0.5
s.b.park <- (sum((post.mcpark-mean(data.post$cpark))^2)/(M-1))^0.5
s.b.larea <- (sum((post.mlarea-mean(data.post$larea))^2)/(M-1))^0.5
s.b.lprice <- (sum((post.mlprice-mean(data.post$lprice))^2)/(M-1))^0.5
#within standard deviation
s.w.scrap <-(sum((post.wcscraplands)^2)/(MT-M))^0.5
s.w.park <-(sum((post.wcpark)^2)/(MT-M))^0.5
s.w.larea <-(sum((post.wlarea)^2)/(MT-M))^0.5
s.w.lprice <-(sum((post.wlprice)^2)/(MT-M))^0.5
#Check the dimensions of variability in the data
sd(data.set$cscraplands)
s.b.scrap
s.w.scrap
sd(data.set$cpark)
s.b.park
s.w.park
sd(data.set$larea)
s.b.larea
s.w.larea
sd(data.set$lprice)
s.b.lprice
s.w.lprice
#Is this as you expected?
#What do you think it looks like for smaller fixed effects units?
#########################################################################
#Panel estimation with postal code area fixed effects
#########################################################################
#plm.post<-plm(form, data=data.set, index=c("post_number","nr"), model="within") #If we did not tell R that the data is a panel
plm.post<-plm(form, data=data.post, model="within") #Here, R knows what the fixed effect unit is as the dataframe is set as a panel
summary(plm.post)
#Clustered standard errors to account for (spatial) correlation within units
# see this website for more discussion: http://www.richard-bluhm.com/clustered-ses-in-r-and-stata-2/
dfc <- (M/(M-1))*((MT-1)/(plm.post$df.residual)) #Degree of freedom correction
vcov_clus<-dfc*vcovHC(plm.post,type="HC0", cluster="group")
coeftest(plm.post, vcov=vcov_clus)
#alternative using ols with dummies (beware of the degrees of freedom)
lm.post<- lm(update(form, . ~. + factor(post_number)), data=data.set)
#Clustered standard errors to account for (spatial) correlation within units
#"Under the hood" - This function is slightly adapted from Mahmood Arai (http://people.su.se/~ma/clustering.pdf)
clx <- function(fm, cluster){ #We must provide a model (fm) and a unit of clustering(cluster)
M <- length(unique(cluster)) #number of clusters
N <- length(cluster) #Number of observations
dfc <- (M/(M-1))*((N-1)/(N-fm$rank)) #Calculating degree of freedom correction
u <- apply(estfun(fm),2, function(x) tapply(x, cluster, sum)) # collecting (y-xb)'X = e'X and calculating the sums by columns by cluster
vcovCL <- dfc*sandwich(fm, meat=crossprod(u)/N) # Calculates the clustered standard errors
coeftest(fm, vcovCL) } #displays estimates with the clustered standard errors
clx(lm.post, data.set$post_number) #Calls the function and applies it to the model as specified
#For comparison, the other models
coeftest(plm.post,vcov=vcov_clus) #Looks pretty similar, don't you think?
summary(lm.simple) #Did it make much difference to include the fixed effects?
#Note: there is no adjustment for spatial correlation in errors in the simple OLS model
#Calculate the clustered errors for the simple model without fixed effects and compare. Does including fixed effects have an impact on spatial correlation? Why/Why not?
clx(lm.simple, data.set$post_number)
##close log file
#sink(type="message")
#sink()
##############################################################
# Exercise 5.1
##############################################################
#Try estimation for another fixed effect unit (e.g. urban_subdivisions, school districts or parish...)
#Compare with postal code fixed effects and discuss with your neighbors
##############################################################
# Generalized additive model
##############################################################
#Define formula
form.gam<- formula(price ~ larea + rebuild_after + cpark + cscraplands +factor(date_year))
#Specifying a GAM
#We want to add the smooth terms...update the formula
#We have to specify an exponential family distribution and a link function, and specify the data set...
gam.1 <- gam(update(form.gam, .~. +s(coord_x,coord_y, k=5)), family=gaussian(link=log), data=data.set)
#Let's have a look..
plot(gam.1, all.terms=TRUE, scheme=2, page=1) #Plots all of the estimates on the scale of the centred smooth, i.e. the shape of the function is informative...
dev.off()
plot(gam.1, scheme=1) # 3D plot
plot(gam.1, scheme=0) # basic (default) plot
#Plotting at the scale of the response (log price) - this command sets the value of the model covariates at their medians - see ?vis.gam() for more
vis.gam(gam.1, view=c("coord_x","coord_y"),
plot.type="contour",
color="heat",
cond=list(rebuild_after=0), #sets the value of dummy rebuild_after to 0
labcex=1,
cex.axis=1.5,
cex.main = 3,
cex.sub=2,
vfont=c("sans serif","bold"),
col="black", lwd=0.9,
main="Spatial smoothing", legend=TRUE,
ylab="", xlab="")
#Diagnostics
gam.check(gam.1)
#look at the plots of the residuals
#Does the distribution look reasonable? Try another one, e.g. Gamma (see ?gam() for alternatives)
#Look at the diagnostics - is k large enough, i.e. are we oversmoothing?
#Check out the objects delivered by the estimation
ls(gam.1)
summary(gam.1$linear.predictor) #This is the log of the dependent variable
summary(data.set$lprice) #for comparison
summary(gam.1$fitted.values) #This is the prediction of the dependent variable
summary(gam.1$y) #This is the dependent variable)
summary(gam.1$residuals) #These are the residuals)
#Diagnostic test of the residuals (they were stored in the model)
gam.res <- gam(gam.1$residuals~s(coord_x,coord_y,k=40), data=data.set, select=TRUE) #Select option allows some smoothes to be dropped (selecting relevant regressors)
plot.gam(gam.res, scheme=1)
summary(gam.res)
##############################################################
# Exercise 5.2
##############################################################
#Discuss with your neighbors:
#Try increasing k: Do you have a pattern in the residuals?
#What happens when increasing k to the estimated parameters?
#Try smoothing other covariates... Hint: Define your own formula, check out ?gam()
# In practice the smoothness selection can vary by optimization method. GVC is one method. One can also use REML or ML (maximum likelihood based methods).
#Read more about GAMs in Simon Wood's book from 2006.
#Check out his website: http://www.maths.bath.ac.uk/~sw283/