# 1. load the appropriate libraries
library(tidyverse)
library(table1)
library(broom)

# 2. use the read_rds file to read the dataset
penguins <- read_rds("data/penguins.rds")

Exercise 1

Use the table1 package to replicate the table below. Use the examples provided in the following vignette. What do you notice from the table? Which species of penguin is the heaviest? Which one has the largest flippers? Which have the largest bill depth? How are the different species distributed across the three islands?

# Write your code to create a histogram of delays

#table1(factor(sex) + factor(island) + body_mass_g + flipper_length_mm + bill_depth_mm, data = penguins)
# table1(factor(sex) + factor(island) + body_mass_g + flipper_length_mm + bill_depth_mm | species, data = penguins)
#--> Error: object 'sex' not found.

table1(~ factor(sex) + factor(island) + body_mass_g + flipper_length_mm + bill_depth_mm | species, data = penguins, overall=FALSE)
Adelie
(N=152)
Chinstrap
(N=68)
Gentoo
(N=124)
factor(sex)
female 73 (48.0%) 34 (50.0%) 58 (46.8%)
male 73 (48.0%) 34 (50.0%) 61 (49.2%)
Missing 6 (3.9%) 0 (0%) 5 (4.0%)
factor(island)
Biscoe 44 (28.9%) 0 (0%) 124 (100%)
Dream 56 (36.8%) 68 (100%) 0 (0%)
Torgersen 52 (34.2%) 0 (0%) 0 (0%)
body_mass_g
Mean (SD) 3700 (459) 3730 (384) 5080 (504)
Median [Min, Max] 3700 [2850, 4780] 3700 [2700, 4800] 5000 [3950, 6300]
Missing 1 (0.7%) 0 (0%) 1 (0.8%)
flipper_length_mm
Mean (SD) 190 (6.54) 196 (7.13) 217 (6.48)
Median [Min, Max] 190 [172, 210] 196 [178, 212] 216 [203, 231]
Missing 1 (0.7%) 0 (0%) 1 (0.8%)
bill_depth_mm
Mean (SD) 18.3 (1.22) 18.4 (1.14) 15.0 (0.981)
Median [Min, Max] 18.4 [15.5, 21.5] 18.5 [16.4, 20.8] 15.0 [13.1, 17.3]
Missing 1 (0.7%) 0 (0%) 1 (0.8%)

Answer: Gentoo is the heaviest among the species, they also have the largest flipper length. The Chinstrap and the Adelie have the largest bill depths. The Chinstrap have a higher mean. The observation with the largest bill depth however belongs to the Adelie.

Exercise 2

  1. Replicate the scatter plot below, coloring the points according to the species. What can you tell about the relationship between bill depth and penguin weight? Comment on the intercepts and the slopes. Do different species have similar intercepts? Slopes? Does the outcome variable appear normally distributed? Why does this matter?
ggplot(data = penguins, aes(bill_depth_mm, body_mass_g, color = species)) + geom_point() + labs(x = 'bill depth', y = 'body mass') +
  geom_smooth(method = 'lm', se = FALSE)

ggplot(data = penguins, aes(bill_depth_mm, body_mass_g, color = species)) + geom_point() + labs(x = 'bill depth', y = 'body mass') +
  geom_smooth(method = 'lm', se = FALSE) +
  scale_color_manual(values = c('Adelie' = 'yellow', 'Chinstrap' = 'red', 'Gentoo' = 'black'))

Answer: There seems to be a positive relationship between bill depth and body mass when controlling for the species. However, the Gentoo have a greater intercept in contrast to Adelie and Chinstrap who share nearly the same intercept. This results in an example of simpsons paradox, where the model without species would indicate a negative relationship between body mass and bill depth. Furthermore, the slope of the Gentoo is also greater than for the other two. I would say the predictor and outcome variable are both normally distributed looking at the mean and median being very close together.

Exercise 3

Now replicate the plot below, describing the relationship between flipper length and body mass, and coloring the data according to the associated species. Facet the plot by island (search online if necessary). Finally, tell a story about the relationship between flipper length and weight in these three penguin species, and the distribution of penguins across the three islands.

ggplot(data = penguins, aes(x = flipper_length_mm, y = body_mass_g, color = species)) + geom_point() + facet_wrap(~island, nrow=2, ncol=2, scale = "free") +
  labs(x = 'Flipper length in mm', y = 'Body mass in g')

Answer: Flipper length also seems to be related to Weight positively and linearly. While you can see the species have different distributions and occur on different islands, the relationship seems to be consistent both within the Adelie species across islands and between the species.

Exercise 4

Replicate the scatter plot below, adding vertical and horizontal lines to indicate the mean of the predictor and of the outcome variable. Show that the linear regression line passes at the intersection of the two means.

mean_flipperlength <- mean(penguins$flipper_length_mm, na.rm = TRUE)
mean_bodymass <- mean(penguins$body_mass_g, na.rm = TRUE)

penguins <- na.omit(penguins)

ggplot(data = penguins, aes(x = flipper_length_mm, y = body_mass_g)) +
  geom_point(aes(color = species), size=2) +
  labs(x = "Flipper Length (mm)", y = "Body Mass (g)", color = "Species") +
  geom_vline(xintercept = mean_flipperlength) +
  geom_hline(yintercept = mean_bodymass) +
  geom_smooth(method = "lm", se = FALSE, color = "blue") +
  theme_minimal() +
  labs(title= 'Flipper length and body weight of different penguin species per island') +
   geom_label(
    aes(x = mean_flipperlength + 5, y = mean_bodymass),
    label = "Mean Body Mass",
    color = "black", size = 5, fill = "grey", hjust =0 , vjust = 0.5)+
   geom_label(
    aes(x = mean_flipperlength - 20, y = mean_bodymass + 1500),
    label = "Mean Flipper Length",
    color = "black", size = 5, fill = "grey", hjust = 0, vjust = 0.5)

Answer: This regression line intersects precisely at the point where the mean flipper length and mean body mass coincide.

Exercise 5

Use the lm function in R to fit a simple linear regression with one predictor. Write up your findings using the template below. Fill in the gaps in the template with the result of your model.

M1 <- lm(body_mass_g ~ flipper_length_mm, data = penguins)

summary(M1)
## 
## Call:
## lm(formula = body_mass_g ~ flipper_length_mm, data = penguins)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -1057.33  -259.79   -12.24   242.97  1293.89 
## 
## Coefficients:
##                   Estimate Std. Error t value Pr(>|t|)    
## (Intercept)       -5872.09     310.29  -18.93   <2e-16 ***
## flipper_length_mm    50.15       1.54   32.56   <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 393.3 on 331 degrees of freedom
## Multiple R-squared:  0.7621, Adjusted R-squared:  0.7614 
## F-statistic:  1060 on 1 and 331 DF,  p-value: < 2.2e-16
tidy(M1, conf.int = TRUE)
## # A tibble: 2 × 7
##   term              estimate std.error statistic   p.value conf.low conf.high
##   <chr>                <dbl>     <dbl>     <dbl>     <dbl>    <dbl>     <dbl>
## 1 (Intercept)        -5872.     310.       -18.9 1.18e- 54  -6482.    -5262. 
## 2 flipper_length_mm     50.2      1.54      32.6 3.13e-105     47.1      53.2
glance(M1)
## # A tibble: 1 × 12
##   r.squared adj.r.squared sigma statistic   p.value    df logLik   AIC   BIC
##       <dbl>         <dbl> <dbl>     <dbl>     <dbl> <dbl>  <dbl> <dbl> <dbl>
## 1     0.762         0.761  393.     1060. 3.13e-105     1 -2461. 4928. 4940.
## # ℹ 3 more variables: deviance <dbl>, df.residual <int>, nobs <int>

Answer: Linear regression was used to test the association between penguin’s body mass (grams) and the length of his flippers (in milimeters) using data from n = 344 Penguins. 75.9% of the variation in body mass was explained by flipper length (R2= 0.759). There was a significant positive association between flipper length and body mass (B = 49.686; 95% CI = 46.7, 52.7 ; p < .001). On average, for every 1-mm difference in flipper length, penguins differ in mean body mass by 49.7 grams.

Exercise 6

Use the lm function in R to fit predict the body mass using a different explanatory variable. Write up your findings using a similar template like the one used above. Which model is better, in your view? This one or the model in the previous question? Justify your answer.

#bill length

EX6 <- lm(body_mass_g ~ bill_depth_mm, data = penguins)
summary(EX6)
## 
## Call:
## lm(formula = body_mass_g ~ bill_depth_mm, data = penguins)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -1616.08  -510.38   -68.67   486.51  1811.12 
## 
## Coefficients:
##               Estimate Std. Error t value Pr(>|t|)    
## (Intercept)    7519.98     342.33  21.967   <2e-16 ***
## bill_depth_mm  -193.01      19.81  -9.741   <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 710.9 on 331 degrees of freedom
## Multiple R-squared:  0.2228, Adjusted R-squared:  0.2205 
## F-statistic: 94.89 on 1 and 331 DF,  p-value: < 2.2e-16
tidy(EX6, conf.int = TRUE)
## # A tibble: 2 × 7
##   term          estimate std.error statistic  p.value conf.low conf.high
##   <chr>            <dbl>     <dbl>     <dbl>    <dbl>    <dbl>     <dbl>
## 1 (Intercept)      7520.     342.      22.0  1.31e-66    6847.     8193.
## 2 bill_depth_mm    -193.      19.8     -9.74 7.02e-20    -232.     -154.
glance(EX6)
## # A tibble: 1 × 12
##   r.squared adj.r.squared sigma statistic  p.value    df logLik   AIC   BIC
##       <dbl>         <dbl> <dbl>     <dbl>    <dbl> <dbl>  <dbl> <dbl> <dbl>
## 1     0.223         0.220  711.      94.9 7.02e-20     1 -2658. 5322. 5334.
## # ℹ 3 more variables: deviance <dbl>, df.residual <int>, nobs <int>

Answer: Linear regression was used to examine the relationship between a penguin’s body mass (in grams) and its bill depth (in millimeters) using data from n = 344 penguins. The analysis revealed that 22.3% of the variability in body mass was accounted for by variations in bill depth (R² = 0.223). The findings indicate a statistically significant negative association between bill depth and body mass (B = -191.64; 95% CI = [-230, -154]; p < .001). On average, for every 1-mm increase in bill depth, penguins exhibit a decrease in mean body mass by 191.64 grams.

Exercise 7

We now want to fit a model with parallel slopes, one slope for each of the three species of penguins. Run the regression as you have done above, but this time, add the species variable as a predictor in your model. (1) Write the equation for the linear model (you will need to replace the coefficients in the formula b0,b1,b2 with their estimates). (2) Write up your findings in a similar manner to the template shown in the previous question. (3) Write a separate model for each of the three species. (4) Use the augment(M2) to see the list of residuals and show that the mean of the residuals is almost zero and its standard deviation is the residual standard error.

M3 <- lm(body_mass_g ~ flipper_length_mm + species, data = penguins)

summary(M3)
## 
## Call:
## lm(formula = body_mass_g ~ flipper_length_mm + species, data = penguins)
## 
## Residuals:
##    Min     1Q Median     3Q    Max 
## -898.8 -252.0  -24.8  229.8 1191.6 
## 
## Coefficients:
##                   Estimate Std. Error t value Pr(>|t|)    
## (Intercept)       -4013.18     586.25  -6.846 3.74e-11 ***
## flipper_length_mm    40.61       3.08  13.186  < 2e-16 ***
## speciesChinstrap   -205.38      57.57  -3.568 0.000414 ***
## speciesGentoo       284.52      95.43   2.981 0.003083 ** 
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 373.3 on 329 degrees of freedom
## Multiple R-squared:  0.787,  Adjusted R-squared:  0.7851 
## F-statistic: 405.3 on 3 and 329 DF,  p-value: < 2.2e-16
tidy(M3, conf.int = TRUE)
## # A tibble: 4 × 7
##   term              estimate std.error statistic  p.value conf.low conf.high
##   <chr>                <dbl>     <dbl>     <dbl>    <dbl>    <dbl>     <dbl>
## 1 (Intercept)        -4013.     586.       -6.85 3.74e-11  -5166.    -2860. 
## 2 flipper_length_mm     40.6      3.08     13.2  3.64e-32     34.5      46.7
## 3 speciesChinstrap    -205.      57.6      -3.57 4.14e- 4   -319.      -92.1
## 4 speciesGentoo        285.      95.4       2.98 3.08e- 3     96.8     472.
glance(M3)
## # A tibble: 1 × 12
##   r.squared adj.r.squared sigma statistic   p.value    df logLik   AIC   BIC
##       <dbl>         <dbl> <dbl>     <dbl>     <dbl> <dbl>  <dbl> <dbl> <dbl>
## 1     0.787         0.785  373.      405. 4.14e-110     3 -2443. 4895. 4914.
## # ℹ 3 more variables: deviance <dbl>, df.residual <int>, nobs <int>
augment(M3)
## # A tibble: 333 × 9
##    body_mass_g flipper_length_mm species .fitted .resid    .hat .sigma   .cooksd
##          <int>             <int> <fct>     <dbl>  <dbl>   <dbl>  <dbl>     <dbl>
##  1        3750               181 Adelie    3337.  413.  0.0125    373. 0.00393  
##  2        3800               186 Adelie    3540.  260.  0.00799   374. 0.000989 
##  3        3250               195 Adelie    3905. -655.  0.00848   372. 0.00664  
##  4        3450               193 Adelie    3824. -374.  0.00742   373. 0.00189  
##  5        3650               190 Adelie    3702.  -52.0 0.00685   374. 0.0000337
##  6        3625               181 Adelie    3337.  288.  0.0125    374. 0.00191  
##  7        4675               195 Adelie    3905.  770.  0.00848   371. 0.00918  
##  8        3200               182 Adelie    3377. -177.  0.0113    374. 0.000652 
##  9        3800               191 Adelie    3743.   57.4 0.00690   374. 0.0000414
## 10        4400               198 Adelie    4027.  373.  0.0111    373. 0.00283  
## # ℹ 323 more rows
## # ℹ 1 more variable: .std.resid <dbl>
augment(M3) %>% 
  summarise(sum_resid = sum(.resid))
## # A tibble: 1 × 1
##       sum_resid
##           <dbl>
## 1 0.00000000121
summary(M3)
## 
## Call:
## lm(formula = body_mass_g ~ flipper_length_mm + species, data = penguins)
## 
## Residuals:
##    Min     1Q Median     3Q    Max 
## -898.8 -252.0  -24.8  229.8 1191.6 
## 
## Coefficients:
##                   Estimate Std. Error t value Pr(>|t|)    
## (Intercept)       -4013.18     586.25  -6.846 3.74e-11 ***
## flipper_length_mm    40.61       3.08  13.186  < 2e-16 ***
## speciesChinstrap   -205.38      57.57  -3.568 0.000414 ***
## speciesGentoo       284.52      95.43   2.981 0.003083 ** 
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 373.3 on 329 degrees of freedom
## Multiple R-squared:  0.787,  Adjusted R-squared:  0.7851 
## F-statistic: 405.3 on 3 and 329 DF,  p-value: < 2.2e-16

Answer: Y = -4031 + 40.7(flipper_length) - 207(Chinstrap) + 267 (Gentoo)

Linear regression was used to examine the relationship between a penguin’s body mass (in grams) with the flipper length (in millimeters) and type of species, using data from n = 344 penguins. The analysis revealed that 78.7% of the variability in body mass was accounted for by variations in flipper length and species (R² = 0.787).

Adelie ==> Y = -4031 + 40.7 (flipper_length)

Chinstrap ==> Y = -4238 + 40.7 (flipper_length)

Gentoo ==> Y = - 3747 + 40.7 (flipper_length)

Exercise 8

Reproduce the parallel slopes image below using the coefficients from the second model M2.

coefs <- coef(M3)

penguins |> 
  ggplot(
    aes(x = flipper_length_mm, y = body_mass_g, color = species)
    ) + 
  geom_point(alpha = 0.5) + 
  # Use the intercept for the reference category (Adelie)
  geom_abline(
    intercept = -4031, slope = 40.7, color = "blue"
    ) +
  # Use the appropriate intercept for Chinstrap
  geom_abline(
    intercept = -4031 + -207, slope = 40.7, color = "red"
    ) +
  # Use the appropriate intercept for Gentoo
  geom_abline(
    intercept = -4031 + 266.810, slope = 40.7, color = "purple"
    ) + 
  scale_color_manual(
    values = c("Adelie" = "blue", "Chinstrap" = "red", "Gentoo" = "purple")
    ) + geom_jitter()

Answer: In the graph we see a clear distinction between the Adelie and Chinstrap penguins versus the Gentoo. While the parallell slopes model fits all the data quite well, the Gentoo seemingly both have a higher weight and longer flippers and are thus distributed along the upper right side of the graph, while the Adelie and Chinstrap share the lower left part. This distinction should be tested in further analysis by i.e. an ANOVA.

Exercise 9

Search online for an explanation of the various plots (for example, this is a good resource, but you may find others). Create a plot for each of the four diagnostic tests, and describe in words what is the purpose of each diagnostic plot. Then interpret the plot: what can we learn from it?

par(mfrow=c(2,2)) # Change the panel layout to 2 x 2
plot(M3, which = 1)
plot(M3, which = 2)
plot(M3, which = 3)
plot(M3, which = 4)

Answer: Firstly, the residuals vs fitted plot shows if there are patterns in our residuals that indicate a nonlinear relationship. This is done by assessing whether or not the residuals are distributed along a horizontal line. While there is a slight bend in our data I do not believe it to be large enough to justify use of a quadratic model. Secondly, there is the QQ plot, which graphically displays if the residuals are normally distributed. This seems to be the case for our model as all the dots follow the line without systematic deviations. Thirdly, we observe the scale location plot to assess homoscedasticity. In our data the residuals seem to be normally distributed along the values, though there is a hole in the center between 4000-4500 grams, likely resembling the different species. Lastly we see a plot of cooks distance, which shows influential values. The observations 40,170, and 315 stand out and we should investigate if these are measurement errors.

Exercise 10

Run the type 3 Anova, discuss and interpret the output you see and link it to the results of the fitted model summary(M5)

summary(M3)
## 
## Call:
## lm(formula = body_mass_g ~ flipper_length_mm + species, data = penguins)
## 
## Residuals:
##    Min     1Q Median     3Q    Max 
## -898.8 -252.0  -24.8  229.8 1191.6 
## 
## Coefficients:
##                   Estimate Std. Error t value Pr(>|t|)    
## (Intercept)       -4013.18     586.25  -6.846 3.74e-11 ***
## flipper_length_mm    40.61       3.08  13.186  < 2e-16 ***
## speciesChinstrap   -205.38      57.57  -3.568 0.000414 ***
## speciesGentoo       284.52      95.43   2.981 0.003083 ** 
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 373.3 on 329 degrees of freedom
## Multiple R-squared:  0.787,  Adjusted R-squared:  0.7851 
## F-statistic: 405.3 on 3 and 329 DF,  p-value: < 2.2e-16
anova <- aov(M3, type = 3)
summary(anova)
##                    Df    Sum Sq   Mean Sq F value   Pr(>F)    
## flipper_length_mm   1 164047703 164047703 1177.31  < 2e-16 ***
## species             2   5368818   2684409   19.27 1.22e-08 ***
## Residuals         329  45843144    139341                     
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Answer: The Anova indicates that for both flipper length and species the difference between the groups is significantly larger than the variation within groups. This supports our previous results from the linear regression.

Exercise 11

Now repeat exercises 6 - 10 but this time analyze the association between the bill depth and the body mass: body_mass_g ~ bill_depth_mm + species

#exercise 7
M6 <- lm(body_mass_g ~ bill_depth_mm + species, data = penguins)

summary(M6)
## 
## Call:
## lm(formula = body_mass_g ~ bill_depth_mm + species, data = penguins)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -846.01 -261.75  -30.43  232.36 1185.55 
## 
## Coefficients:
##                   Estimate Std. Error t value Pr(>|t|)    
## (Intercept)      -1000.846    324.968  -3.080  0.00225 ** 
## bill_depth_mm      256.551     17.637  14.546  < 2e-16 ***
## speciesChinstrap     8.111     52.874   0.153  0.87817    
## speciesGentoo     2245.878     73.956  30.368  < 2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 360 on 329 degrees of freedom
## Multiple R-squared:  0.8019, Adjusted R-squared:  0.8001 
## F-statistic: 443.9 on 3 and 329 DF,  p-value: < 2.2e-16
tidy(M6, conf.int = TRUE)
## # A tibble: 4 × 7
##   term             estimate std.error statistic  p.value conf.low conf.high
##   <chr>               <dbl>     <dbl>     <dbl>    <dbl>    <dbl>     <dbl>
## 1 (Intercept)      -1001.       325.     -3.08  2.25e- 3  -1640.      -362.
## 2 bill_depth_mm      257.        17.6    14.5   2.33e-37    222.       291.
## 3 speciesChinstrap     8.11      52.9     0.153 8.78e- 1    -95.9      112.
## 4 speciesGentoo     2246.        74.0    30.4   1.89e-97   2100.      2391.
glance(M6)
## # A tibble: 1 × 12
##   r.squared adj.r.squared sigma statistic   p.value    df logLik   AIC   BIC
##       <dbl>         <dbl> <dbl>     <dbl>     <dbl> <dbl>  <dbl> <dbl> <dbl>
## 1     0.802         0.800  360.      444. 2.85e-115     3 -2431. 4871. 4890.
## # ℹ 3 more variables: deviance <dbl>, df.residual <int>, nobs <int>
augment(M6)
## # A tibble: 333 × 9
##    body_mass_g bill_depth_mm species .fitted .resid    .hat .sigma    .cooksd
##          <int>         <dbl> <fct>     <dbl>  <dbl>   <dbl>  <dbl>      <dbl>
##  1        3750          18.7 Adelie    3797.  -46.7 0.00715   361. 0.0000304 
##  2        3800          17.4 Adelie    3463.  337.  0.00900   360. 0.00201   
##  3        3250          18   Adelie    3617. -367.  0.00714   360. 0.00188   
##  4        3450          19.3 Adelie    3951. -501.  0.00903   360. 0.00444   
##  5        3650          20.6 Adelie    4284. -634.  0.0190    359. 0.0153    
##  6        3625          17.8 Adelie    3566.   59.2 0.00757   361. 0.0000520 
##  7        4675          19.6 Adelie    4028.  647.  0.0106    359. 0.00877   
##  8        3200          17.6 Adelie    3514. -314.  0.00819   360. 0.00159   
##  9        3800          21.2 Adelie    4438. -638.  0.0264    359. 0.0219    
## 10        4400          21.1 Adelie    4412.  -12.4 0.0250    361. 0.00000779
## # ℹ 323 more rows
## # ℹ 1 more variable: .std.resid <dbl>
mean(M6$residuals)
## [1] 6.06513e-15
sd(M6$residuals)
## [1] 358.3959
#exercise 8
penguins |> 
  ggplot(
    aes(x = bill_depth_mm, y = body_mass_g, color = species)
    ) + 
  geom_point() + 
  # Use the intercept for the reference category (Adelie)
  geom_abline(
    intercept = -1007, slope = 256.61, color = "#ffc62a"
    ) +
  # Use the appropriate intercept for Chinstrap
  geom_abline(
    intercept = -1007 + 13, slope = 256.61, color = "#ff5733"
    ) +
  # Use the appropriate intercept for Gentoo
  geom_abline(
    intercept = -1007 + 2238, slope = 256.61, color = "#351603"
    )+
 scale_color_manual(
   values = c("#ffc62a","#ff5733", "#351603")
 )

#exercise 9
par(mfrow=c(2,2)) # Change the panel layout to 2 x 2
plot(M6, which = 1)
plot(M6, which = 2)
plot(M6, which = 3)
plot(M6, which = 4)

#exercise10
summary(M6)
## 
## Call:
## lm(formula = body_mass_g ~ bill_depth_mm + species, data = penguins)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -846.01 -261.75  -30.43  232.36 1185.55 
## 
## Coefficients:
##                   Estimate Std. Error t value Pr(>|t|)    
## (Intercept)      -1000.846    324.968  -3.080  0.00225 ** 
## bill_depth_mm      256.551     17.637  14.546  < 2e-16 ***
## speciesChinstrap     8.111     52.874   0.153  0.87817    
## speciesGentoo     2245.878     73.956  30.368  < 2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 360 on 329 degrees of freedom
## Multiple R-squared:  0.8019, Adjusted R-squared:  0.8001 
## F-statistic: 443.9 on 3 and 329 DF,  p-value: < 2.2e-16
anovaBD <- aov(M6, type = 3)
summary(anovaBD)
##                Df    Sum Sq  Mean Sq F value Pr(>F)    
## bill_depth_mm   1  47959592 47959592   370.0 <2e-16 ***
## species         2 124655460 62327730   480.9 <2e-16 ***
## Residuals     329  42644614   129619                   
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Answer: Linear regression was used to examine the relationship between a penguin’s body mass (in grams) and its bill depth (in millimeters) while controlling for species using data from n = 344 penguins. The analysis revealed that 80% of the variability in body mass was accounted for by variations in bill depth (R² = 0.8001) when the species is controlled for. The findings indicate a statistically significant positive association between bill depth and body mass (B = 256.55; 95% CI = [221.98, 291.12]; p < .001). The species differ in their y-axis intercept. The baseline is made up by the Adelie penguins (B0 = -1000.85; 95% CI = [-363.9087, -1637.783]; p < .01]. The Chinstrap penguins do not significantly differ from the Adelie penguins (BChinstrap = 8.111; 95% CI = [-95.52, 111.74]; p > 0.8) The Gentoo have a significantly higher body mass than the other two species (BGentoo = 2245.88; 95% CI = [2100.92, 2390.83]; p < 0.001) Thus, on average, for every 1-mm increase in bill depth, penguins of the same species exhibit an increase in mean body mass by 256.55 grams. The Adelie and Chinstrap penguins have a y-axis intercept of -1000.85 and -992.74, respectively, while the Gentoo have an intercept of 1145.03.

Like with the flipper length, we see a clear distinction between the Adelie and Chinstrap penguins versus the Gentoo. They show a much higher body weight at a lower bill depth.

The Residuals vs Fitted plot shows a straight horizontal line giving us an indication for an appropriate fit of a linear model for this data. Rhe QQ Plot, shows a straight line, indicating normal distribution of the residuals. The Scale-Location plot shows a normal distribution at each stratum of X, indicating homoscedasticity. Lastly, looking at Cooks distance, the observations 76,164, and 282 stand out and we should investigate if these are measurement errors.

The Anova indicates that for both bill depth and species the difference between the groups is significantly larger than the variation within groups. This supports our previous results from the linear regression, indicating both are significant predictors of body weight.

In summary there seems to be a much bigger difference between the species in this model. The Gentoo species runs entirely seperately from the other two. Thus, it might be a better model to combine Adelie and Chinstrap penguins while excluding Gentoo.