Q5.(a)

library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.3     ✔ readr     2.1.4
## ✔ forcats   1.0.0     ✔ stringr   1.5.0
## ✔ ggplot2   3.4.4     ✔ tibble    3.2.1
## ✔ lubridate 1.9.3     ✔ tidyr     1.3.0
## ✔ purrr     1.0.2     
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
# Read the data
bodyfat <- read_table("C:\\Users\\MD IMRAN\\Documents\\bodyfat.txt")
## 
## ── Column specification ────────────────────────────────────────────────────────
## cols(
##   bfat = col_double(),
##   age = col_double(),
##   weight = col_double(),
##   height = col_double(),
##   neck = col_double(),
##   abdomen = col_double(),
##   knee = col_double(),
##   ankle = col_double()
## )
# Fit the regression model
fit <- lm(bfat ~ ., data = bodyfat)

# Summary of the model
summary(fit)
## 
## Call:
## lm(formula = bfat ~ ., data = bodyfat)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -8.1016 -2.9148 -0.7392  3.3351  8.4197 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept) -5.63842   23.98381  -0.235  0.81474    
## age          0.04397    0.03812   1.154  0.25212    
## weight      -0.07294    0.06756  -1.080  0.28356    
## height      -0.69440    0.26036  -2.667  0.00926 ** 
## neck        -0.56477    0.33051  -1.709  0.09137 .  
## abdomen      0.86684    0.12923   6.708 2.57e-09 ***
## knee         0.47829    0.36361   1.315  0.19214    
## ankle        0.31149    0.25267   1.233  0.22126    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 4.188 on 80 degrees of freedom
## Multiple R-squared:  0.8097, Adjusted R-squared:  0.7931 
## F-statistic: 48.64 on 7 and 80 DF,  p-value: < 2.2e-16
# Confidence interval for the change in percent body fat with each year of age
confint(fit, "Age", level = 0.95)
##     2.5 % 97.5 %
## Age    NA     NA
 # Tom's information
Tom <- c(49, 188, 68, 37, 90, 38, 24)
newx_tom <- data.frame(t(Tom))
names(newx_tom) <- colnames(bodyfat)[2:8]

# Bill's information
Bill <- c(40, 220, 76, 40, 113, 34, 20)
newx_bill <- data.frame(t(Bill))
names(newx_bill) <- colnames(bodyfat)[2:8]

# Predict percent body fat and obtain prediction intervals
predict_tom <- predict(fit, newdata = newx_tom, interval = "prediction", level = 0.95)
predict_bill <- predict(fit, newdata = newx_bill, interval = "prediction", level = 0.95)

predict_tom
##       fit      lwr      upr
## 1 18.3547 9.414201 27.29521
predict_bill
##        fit      lwr      upr
## 1 25.15361 14.33843 35.96878

Q7.

 # Correlation Plot
library(corrplot)
## Warning: package 'corrplot' was built under R version 4.3.2
## corrplot 0.92 loaded
# Calculate the correlation matrix
cor_matrix <- cor(bodyfat)

# Create a correlation plot
corrplot(cor_matrix, method = 'number')

#This code generates a correlation matrix for the variables in the bodyfat dataset and then uses the corrplot package to create a visual representation of the correlation matrix.

#The correlation matrix shows the pairwise correlations between different variables in the dataset.
#The color and number in each cell indicate the strength and direction of the correlation. Positive correlations are typically shown in one color, and negative correlations in another.
#The closer the number is to 1 or -1, the stronger the correlation. A value of 1 indicates a perfect positive correlation, while -1 indicates a perfect negative correlation.
#The variables that are highly correlated may have a relationship that could impact the regression model.

# Assuming 'fit' is the name of your regression model
library(GGally)
## Warning: package 'GGally' was built under R version 4.3.2
## Registered S3 method overwritten by 'GGally':
##   method from   
##   +.gg   ggplot2
# Create a coefficient plot for the regression model
ggcoef(fit, exclude_intercept = TRUE)

#This code uses the ggcoef function from the GGally package to create a coefficient plot for the regression model. The exclude_intercept = TRUE argument is used to exclude the intercept term from the plot.

#The coefficient plot displays the estimated coefficients of the predictors in the regression model.
#Each point on the plot represents a coefficient, and the vertical line through the point represents the confidence interval for that coefficient.
#If the confidence interval does not include zero, the corresponding predictor is considered statistically significant.
#The plot allows for a quick visual assessment of the impact and significance of each predictor on the response variable.
#Positive coefficients indicate a positive relationship with the response variable, while negative coefficients indicate a negative relationship.

Q8.(a) This data is likely from an observational study since the researchers are not manipulating any variables. They are observing and recording information on fuel consumption, drivers, income, miles, population, and gasoline tax rates for different states.

 library(tidyverse)

# Read the data and transform variables
driving <- read_table("C:\\Users\\MD IMRAN\\AppData\\Local\\RStudio\\fuel2001.txt") %>%
  mutate(Drivers = Drivers / Pop,
         FuelC = FuelC / Pop,
         Miles = log2(Miles),
         Pop = NULL,
         MPC = NULL)
## 
## ── Column specification ────────────────────────────────────────────────────────
## cols(
##   Drivers = col_double(),
##   FuelC = col_double(),
##   Income = col_double(),
##   Miles = col_double(),
##   MPC = col_double(),
##   Pop = col_double(),
##   Tax = col_double(),
##   State = col_character()
## )
# Select only numeric variables for the scatterplot matrix
numeric_vars <- select_if(driving, is.numeric)

# Scatterplot matrix
pairs(numeric_vars)

#This code creates a scatterplot matrix using the pairs() function, allowing you to visually inspect the relationships between variables. Specifically at the scatterplot involving state gasoline tax and fuel use (FuelC) to assess the relationship.
# Fit the regression model
fit <- lm(FuelC ~ ., data = driving)

# Summary of the model
summary(fit)
## 
## Call:
## lm(formula = FuelC ~ ., data = driving)
## 
## Residuals:
## ALL 51 residuals are 0: no residual degrees of freedom!
## 
## Coefficients: (4 not defined because of singularities)
##                       Estimate Std. Error t value Pr(>|t|)
## (Intercept)          3.268e+00        NaN     NaN      NaN
## Drivers             -2.638e+00        NaN     NaN      NaN
## Income              -1.457e-05        NaN     NaN      NaN
## Miles                8.237e-02        NaN     NaN      NaN
## Tax                 -4.873e-02        NaN     NaN      NaN
## StateAlaska         -3.365e-01        NaN     NaN      NaN
## StateArizona        -2.982e-01        NaN     NaN      NaN
## StateArkansas       -1.006e-01        NaN     NaN      NaN
## StateCalifornia     -5.494e-01        NaN     NaN      NaN
## StateColorado        1.605e-01        NaN     NaN      NaN
## StateConnecticut     5.464e-01        NaN     NaN      NaN
## StateDelaware        3.418e-01        NaN     NaN      NaN
## StateDist_of_Col    -4.565e-01        NaN     NaN      NaN
## StateFlorida        -3.584e-01        NaN     NaN      NaN
## StateGeorgia        -6.685e-01        NaN     NaN      NaN
## StateHawaii         -4.556e-01        NaN     NaN      NaN
## StateIdaho           9.421e-02        NaN     NaN      NaN
## StateIllinois       -5.916e-01        NaN     NaN      NaN
## StateIndiana        -5.191e-01        NaN     NaN      NaN
## StateIowa           -3.525e-01        NaN     NaN      NaN
## StateKansas         -2.447e-01        NaN     NaN      NaN
## StateKentucky       -4.955e-01        NaN     NaN      NaN
## StateLouisiana      -5.173e-01        NaN     NaN      NaN
## StateMaine           3.011e-02        NaN     NaN      NaN
## StateMaryland       -2.623e-02        NaN     NaN      NaN
## StateMassachusetts   3.533e-02        NaN     NaN      NaN
## StateMichigan       -2.472e-01        NaN     NaN      NaN
## StateMinnesota      -4.898e-01        NaN     NaN      NaN
## StateMississippi    -4.438e-01        NaN     NaN      NaN
## StateMissouri       -3.713e-01        NaN     NaN      NaN
## StateMontana         2.875e-01        NaN     NaN      NaN
## StateNebraska        1.314e-01        NaN     NaN      NaN
## StateNevada          1.788e-01        NaN     NaN      NaN
## StateNew_Hampshire   2.966e-01        NaN     NaN      NaN
## StateNew_Jersey     -5.645e-01        NaN     NaN      NaN
## StateNew_Mexico     -3.330e-01        NaN     NaN      NaN
## StateNew_York       -7.380e-01        NaN     NaN      NaN
## StateNorth_Carolina  4.527e-02        NaN     NaN      NaN
## StateNorth_Dakota   -1.700e-01        NaN     NaN      NaN
## StateOhio           -2.760e-01        NaN     NaN      NaN
## StateOklahoma       -6.734e-01        NaN     NaN      NaN
## StateOregon          5.101e-02        NaN     NaN      NaN
## StatePennsylvania   -2.042e-01        NaN     NaN      NaN
## StateRhode_Island    1.299e-01        NaN     NaN      NaN
## StateSouth_Carolina -3.287e-01        NaN     NaN      NaN
## StateSouth_Dakota    2.404e-02        NaN     NaN      NaN
## StateTennessee      -1.412e-01        NaN     NaN      NaN
## StateTexas          -5.024e-01        NaN     NaN      NaN
## StateUtah            6.791e-02        NaN     NaN      NaN
## StateVermont         4.884e-01        NaN     NaN      NaN
## StateVirginia       -2.603e-01        NaN     NaN      NaN
## StateWashington             NA         NA      NA       NA
## StateWest_Virginia          NA         NA      NA       NA
## StateWisconsin              NA         NA      NA       NA
## StateWyoming                NA         NA      NA       NA
## 
## Residual standard error: NaN on 0 degrees of freedom
## Multiple R-squared:      1,  Adjusted R-squared:    NaN 
## F-statistic:   NaN on 50 and 0 DF,  p-value: NA
#The p-values in the summary output to identify predictors with a significant impact on fuel consumption. The coefficients provide information about the relationship between each predictor and fuel use, controlling for other predictors.

(d)The R-squared value (R²) represents the proportion of the variance in the response variable (FuelC) that is explained by the predictors in the model. A higher R² indicates a better fit.

  # Find the state with the lowest tax rate
lowest_tax_state <- driving %>%
  slice_min(Tax)

# Find the state with the highest tax rate
highest_tax_state <- driving %>%
  slice_max(Tax)

# Predicted values
predicted_lowest_tax <- predict(fit, newdata = lowest_tax_state)
predicted_highest_tax <- predict(fit, newdata = highest_tax_state)
## Warning in predict.lm(fit, newdata = highest_tax_state): prediction from
## rank-deficient fit; attr(*, "non-estim") has doubtful cases
# Actual values
actual_lowest_tax <- lowest_tax_state$FuelC
actual_highest_tax <- highest_tax_state$FuelC

# Display the results
cat("Lowest Tax State - Predicted Fuel Consumption:", predicted_lowest_tax, "\n")
## Lowest Tax State - Predicted Fuel Consumption: 0.7509074
cat("Lowest Tax State - Actual Fuel Consumption:", actual_lowest_tax, "\n\n")
## Lowest Tax State - Actual Fuel Consumption: 0.7509074
cat("Highest Tax State - Predicted Fuel Consumption:", predicted_highest_tax, "\n")
## Highest Tax State - Predicted Fuel Consumption: 0.4823269
cat("Highest Tax State - Actual Fuel Consumption:", actual_highest_tax, "\n")
## Highest Tax State - Actual Fuel Consumption: 0.4823269