Consider the 𝚖𝚝𝚌𝚊𝚛𝚜 data set. Fit a model with mpg as the outcome that includes number of cylinders as a factor variable and weight as confounder. Give the adjusted estimate for the expected change in mpg comparing 8 cylinders to 4.:

Question1:

data(mtcars)
mtcars$cyl = as.factor(mtcars$cyl)
fit = lm(mpg~factor(cyl)+wt,data=mtcars)
summary(fit)$coefficients[3]
## [1] -6.07086

Question2:

Consider the 𝚖𝚝𝚌𝚊𝚛𝚜 data set. Fit a model with mpg as the outcome that includes number of cylinders as a factor variable and weight as a possible confounding variable. Compare the effect of 8 versus 4 cylinders on mpg for the adjusted and unadjusted by weight models. Here, adjusted means including the weight variable as a term in the regression model and unadjusted means the model without weight included. What can be said about the effect comparing 8 and 4 cylinders after looking at models with and without weight included?.

fit2 = lm(mpg ~ factor(cyl)+ wt, data=mtcars) 
fit3 = lm(mpg ~ factor(cyl), data=mtcars)
summary(fit2)$coefficients[3]
## [1] -6.07086
summary(fit3)$coefficients[3]
## [1] -11.56364
#ans = Holding weight constant, cylinder appears to have less of an impact on mpg than if weight is disregarded.

Question3:

Consider the 𝚖𝚝𝚌𝚊𝚛𝚜 data set. Fit a model with mpg as the outcome that considers number of cylinders as a factor variable and weight as confounder. Now fit a second model with mpg as the outcome model that considers the interaction between number of cylinders (as a factor variable) and weight. Give the P-value for the likelihood ratio test comparing the two models and suggest a model using 0.05 as a type I error rate significance benchmark.

fit4 = lm(mpg~factor(cyl)*wt, data=mtcars)
anova(fit2,fit4, test="Chisq")
## Analysis of Variance Table
## 
## Model 1: mpg ~ factor(cyl) + wt
## Model 2: mpg ~ factor(cyl) * wt
##   Res.Df    RSS Df Sum of Sq Pr(>Chi)
## 1     28 183.06                      
## 2     26 155.89  2     27.17   0.1038
#The P-value is small (less than 0.05). So, according to our criterion, we reject, which suggests that the interaction term is necessary

Question4:

Consider the 𝚖𝚝𝚌𝚊𝚛𝚜 data set. Fit a model with mpg as the outcome that includes number of cylinders as a factor variable and weight inlcuded in the model as

fit5 = lm(mpg ~ I(wt * 0.5) + factor(cyl), data = mtcars)
#ans: The estimated expected change in MPG per one ton increase in weight for a specific number of cylinders (4, 6, 8).

Question5:

Consider the following data set

x <- c(0.586, 0.166, -0.042, -0.614, 11.72)
y <- c(0.549, -0.026, -0.127, -0.751, 1.344)

Give the hat diagonal for the most influential point

fit6=lm(y~x)
dfit = dffits(fit6)
max =  max(abs(dfit))
hatvalues(fit6)[which(abs(dfit)==max)]
##         5 
## 0.9945734

Question6:

Consider the following data set

x <- c(0.586, 0.166, -0.042, -0.614, 11.72)
y <- c(0.549, -0.026, -0.127, -0.751, 1.344)
dfbetas(fit6)[which(hatvalues(fit6)==max(hatvalues(fit6))),2]
## [1] -133.8226