# Rexample.R April 2016
# First remove all variables from the workspace
rm(list=ls())
# Read in data, summarize
y = c(1,2,2,2,3)
x = c(1,2,3,4,5)
y
mean(y)
summary(y)
plot(y,x)
# OLS Regression with limited output
lm(y~x)
# Assign OLS results to an object called lm.cars
lm.cars <- lm(y~x)
# Now print out some of the results held in the object
summary(lm.cars)
# This is not all the object has
names(lm.cars)
# This includes coefficients and fitted.values that we list
lm.cars$coefficients
lm.cars$fitted.values
# Heteroskedastic-consistent standard errors
# Package sandwich gives Het robust variance matrix
# Then need to compute standard errors
install.packages("sandwich") # Not necessary if already installed
library(sandwich)
model <- lm(y ~x)
vcovHC(model)
sqrt(diag(vcovHC(model)))
# Easier is use package lmtest
install.packages("lmtest") # Not necessary if already installed
library(lmtest)
coeftest(model, vcov=vcovHC)
# OLS with matrix algebra
# First add an intercept
x
X <- cbind(1,x)
X
# solve is matrix inversion
# t(X) is transpose of X
# %*% is matrix multiplication
bhat <- solve(t(X)%*%X)%*%t(X)%*%y
bhat
# Read in a comma-separated values file
# mydata <- read.csv("carsdata.csv")
mydata <- read.csv("http://cameron.econ.ucdavis.edu/excel/carsdata.csv")
summary(mydata)
mydata
# Following does not work
lm(CARS~HHSIZE)
# Need to say where data comes from
lm(CARS~HHSIZE, data=mydata)
# Or simplest is to first attach names
attach(mydata)
lm(CARS~HHSIZE)