- 11th Nov 2022
- 06:03 am
rm(list = ls())
setwd("d:/Documents/R/")
a8 <- read.table("Assignment_VIII.txt", sep = '\t' , header = TRUE, stringsAsFactors = FALSE)
#transform variables
a8$lnSales<-log(a8$Sales)
a8$lnAdvertising<-log(a8$Advertising)
attach(a8)
#regression models
reg1<-lm(Sales~Advertising)
reg2<-lm(Sales~lnAdvertising)
reg3<-lm(lnSales~Advertising)
reg4<-lm(lnSales~lnAdvertising)
#compare models
if (!require("outreg")) install.packages("outreg")
library(outreg)
stargazer(reg1, reg2, reg3, reg4, type="html", out="a8.doc")
#scatterplot
ggplot(a8, aes(x = Advertising, y = Sales)) +
geom_point(shape = 25, colour = "blue", fill = "violet") +
geom_smooth(method = lm, col = "red")
#scatterplot matrix
# Correlation panel
panel.cor <- function(x, y){
usr <- par("usr"); on.exit(par(usr))
par(usr = c(0, 1, 0, 1))
r <- round(cor(x, y), digits=2)
txt <- paste0("R = ", r)
cex.cor <- 0.8/strwidth(txt)
text(0.5, 0.5, txt, cex = cex.cor * r)
}
# Customize upper panel
upper.panel<-function(x, y){
points(x,y, pch = 19, col = "blue")
}
# Create the plots
pairs(a8,
lower.panel = panel.cor,
upper.panel = upper.panel)
#diagnostic plots
library(ggfortify)
if (!require("gridExtra")) install.packages("gridExtra")
library(gridExtra)
p1<-autoplot(reg1, label.size = 3)
grid.arrange(grobs = p1@plots, top = "Diagnostic plots for reg1: Sales on Advertising")
p2<-autoplot(reg2, label.size = 3)
grid.arrange(grobs = p2@plots, top = "Diagnostic plots for reg2: Sales on ln(Advertising)")
p3<-autoplot(reg3, label.size = 3)
grid.arrange(grobs = p3@plots, top = "Diagnostic plots for reg3: ln(Sales) on Advertising")
p4<-autoplot(reg4, label.size = 3)
grid.arrange(grobs = p4@plots, top = "Diagnostic plots for reg4: ln(Sales) on ln(Advertising)")