Recovering Marginal Effects and Standard Errors of Interactions Terms Pt. II: Implement and Visualize
[This article was first published on Journal - R, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
In the last post I presented a function for recovering marginal effects of interaction terms. Here we implement the function with simulated data and plot the results using ggplot2.
#---Simulate Data and Fit a linear model with an interaction term y<-rnorm(100,5,1) x<-rnorm(100,5,1) d<-data.frame(y=y,x=x,fac=sample(letters[1:3],100,replace=T)) mod<-lm(y~x*fac,data=d) #======================================================== #---Extract the Main Effects, including the baseline, into a data.frame dusp<-funinteff(mod,'x') #returns a data.frame of the Estimate and Standard Error, row.names correspond to the variables #----Now Set the data up to visualize in ggplot----- library(ggplot2) #------Quick ggplot (move into graph code later) #quick convenience function to compute significance at .95 funsig<-function(d){ tstat<-abs(d$b/d$se) sig<-ifelse(tstat>=1.96,'yes','no') return(sig) } names(dusp)[1:2]<-c('b','se') #change the names to to make typing easier #Add confidence intervals and signficance test dusp$hi<-dusp$b+1.96*dusp$se dusp$lo<-dusp$b-1.96*dusp$se dusp$sig95<-funsig(dusp) dusp$var<-row.names(dusp) pd<-dusp p1<-ggplot(data=pd,aes(x=var,y=b,shape=sig95)) p1<-p1+geom_hline(yintercept=0,col='grey')+geom_line() p1<-p1+geom_pointrange(aes(ymin=lo,ymax=hi)) #+coord_flip() #uncomment coord_flip to switch the axes p1<-p1+scale_y_continuous(name='Marginal Effect of Interaction Terms')
To leave a comment for the author, please follow the link and comment on their blog: Journal - R.
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.