Skip to content

Instantly share code, notes, and snippets.

@BioSciEconomist
Created October 31, 2016 01:25
Show Gist options
  • Save BioSciEconomist/07f43dbee871495ba90478ed0fa323fa to your computer and use it in GitHub Desktop.
Save BioSciEconomist/07f43dbee871495ba90478ed0fa323fa to your computer and use it in GitHub Desktop.
A Toy Instrumental Variable Application
# r code to support post: http://econometricsense.blogspot.com/2013/06/an-toy-instrumental-variable-application.html
# ------------------------------------------------------------------
# | PROGRAM NAME: R_INSTRUMENTAL_VAR
# | DATE:6/17/13
# | CREATED BY: MATT BOGARD
# | PROJECT FILE: P:\BLOG\STATISTICS
# |----------------------------------------------------------------
# | PURPOSE: BASIC EXAMPLE OF IV
# |
# |
# |------------------------------------------------------------------
setwd('P:\\BLOG\\STATISTICS')
CAMP <- read.table("mplan.txt", header =TRUE)
summary(lm(CAMP$RET~CAMP$CAMP + CAMP$INDEX)) # true B1
summary(lm(CAMP$RET~CAMP$CAMP)) # biased OLS estimate for B1
cor(CAMP$CAMP,CAMP$Z) # is the treatment correlated with the instrument?
cor(CAMP$INDEX,CAMP$Z) # is the instrument correlated with the omitted variable
cov(CAMP$RET,CAMP$Z)/var(CAMP$Z) # y = bZ
cov(CAMP$CAMP,CAMP$Z)/var(CAMP$Z) # x = bZ
# empirical estiamte of B1(IV)
(cov(CAMP$RET,CAMP$Z)/var(CAMP$Z))/(cov(CAMP$CAMP,CAMP$Z)/var(CAMP$Z)) # B1(IV)
# or
(cov(CAMP$RET,CAMP$Z))/(cov(CAMP$CAMP,CAMP$Z))
# two stage regression with IV substitution
# x^ = b1Z
CAMP_IV <- predict(lm(CAMP$CAMP~CAMP$Z)) # produce a vector of estimates for x
# y = b1 x^
# y = b1 x^
lm(CAMP$RET~CAMP_IV)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment