Skip to content

Instantly share code, notes, and snippets.

@cigrainger
Created December 5, 2014 16:03
Show Gist options
  • Save cigrainger/f367e725e8f33d7e47da to your computer and use it in GitHub Desktop.
Save cigrainger/f367e725e8f33d7e47da to your computer and use it in GitHub Desktop.
install.packages('stargazer')
states <- state.name
# states <- c(states,states)
states <- rep(times=2,x=states)
variable <- c(rep('x',50),rep('y',50))
# Create a dataframe called df consisting of states and variable.
df <- data.frame(states,variable)
# Two vectors each of length 100 called X2010 and X2011,
# composed of random numbers -- X2010 is 1-1000, and X2011 is 1000-2000.
# X2011 should be sampling with replacement.
X2010 <- sample(1:1000,100)
X2011 <- sample(1000:2000,100,replace=TRUE)
# Bind X2010 and X2011 to df
df <- cbind(df,X2010,X2011)
# Split df into df1 and df2 where df1 is all values with variable 'x'
# and df2 is all values with variable 'y'
# Combine them back together using bind
df1 <- df[df$variable=='x',]
df2 <- df[df$variable=='y',]
df <- rbind(df1,df2)
# Create vector X2012 of length 50 and it should consist of random values
# from a normal distribution with mean 100 and standard deviation of 10.
X2012 <- rnorm(50,mean=100,sd=10)
states <- state.name
df1 <- data.frame(states,X2012)
# Create a new dataframe df which is a merge of df and df1
df <- merge(df,df1,by='states')
head(df)
# Change df to long form.
df <- melt(df,id.vars=c('states','variable'),variable.name='year')
# substr() and gsub()
?substr
df$year <- substr(df$year,2,5)
df <- dcast(df,states+year~variable)
install.packages('ggplot2')
library(ggplot2)
ggplot(df,aes(x=x,y=y,color=year)) + geom_point() + geom_smooth(method='lm')
fit <- lm(y ~ x,data=df)
summary(fit)
install.packages('stargazer')
library(stargazer)
stargazer(fit,type='html',out='test.html')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment