### Installing relevant packages for data analysis and visualization
library(ggplot2)
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(ggfortify)

### Importing the relevant dataset to reproduce ANOVA and ANCOVA 
growth <- read.csv("~/Desktop/Year 5/BIO4259A/datasets-master/growth.csv")

Preliminary data assessment

### Preliminary viewing of the data
glimpse(growth)
## Rows: 48
## Columns: 3
## $ supplement <chr> "supergain", "supergain", "supergain", "supergain", "contro…
## $ diet       <chr> "wheat", "wheat", "wheat", "wheat", "wheat", "wheat", "whea…
## $ gain       <dbl> 17.37125, 16.81489, 18.08184, 15.78175, 17.70656, 18.22717,…
### supplement and diet being read as character viariables rather than factors
growth <- mutate(growth,
                 supplement = as.factor(supplement), 
                 diet = as.factor(diet))
               
### Now being read as factors with different levels
glimpse(growth)
## Rows: 48
## Columns: 3
## $ supplement <fct> supergain, supergain, supergain, supergain, control, contro…
## $ diet       <fct> wheat, wheat, wheat, wheat, wheat, wheat, wheat, wheat, whe…
## $ gain       <dbl> 17.37125, 16.81489, 18.08184, 15.78175, 17.70656, 18.22717,…
levels(growth$supplement)
## [1] "agrimore"  "control"   "supergain" "supersupp"
### Reordering the levels so that control is seen as the reference
growth <- mutate(growth, 
                 supplement = relevel(supplement, ref = "control"))

### now control is seen as the reference level 
levels(growth$supplement)
## [1] "control"   "agrimore"  "supergain" "supersupp"

1. Generating the ANOVA using the growth.csv dataset

For this I also apply steps 1, 2, 3, 6 and 7 of the Zuur Workflow

Assessing Outliers in X, Y and the homogeneity of Y

### We can visually make a boxplot to asses the range of values that X and Y take, seperating 
### based on the diets in each level

ggplot(growth, aes(x = supplement, y = gain, fill = diet)) +
  geom_boxplot() +
  labs(x = "Supplement", y = "Gain", title = "Boxplot of the effect of supplement on Cow mass Gain") +
  theme_classic()

### The vertical spread among all groups looks about the same which validates the 
### assumption of homogeneity among the variance. Two observations appear to 
### have outliers in their data, but given the four (n=4) replicates in each conditon
### these more likely are reflective of normal variation.

Checking the normality of Y

### Making a histogram to assess the distribution of values among the dependent 
### variable 

ggplot(growth, aes(x = gain)) +
  geom_histogram(bins = 10, fill = 'orange', colour = 'black') +
  labs(x = "Weight Gain", y = "Frequency", title = "Distribution of Weight Gain") +
  theme_classic()

### Here we can observe that weight gain is roughly symmetrical with a unimodal 
### distribution. ANOVA will be be used later to verify normality of the model

Summarizing the data, and checking the relationships between X and Y

### Creating a summary of the data as a new dataframe
sumMoo <- growth %>%
  group_by(diet, supplement) %>%
  summarise(meanGrow = mean (gain))
## `summarise()` has regrouped the output.
## ℹ Summaries were computed grouped by diet and supplement.
## ℹ Output is grouped by diet.
## ℹ Use `summarise(.groups = "drop_last")` to silence this message.
## ℹ Use `summarise(.by = c(diet, supplement))` for per-operation grouping
##   (`?dplyr::dplyr_by`) instead.
### Alternative visualization using dots and lines to conenct each group
ggplot(sumMoo, aes(x = supplement, y = meanGrow, colour = diet, group = diet)) + 
  geom_point(shape = 21, size = 3, colour = 'black') +
  geom_line(size = 0.5) +
  labs(x = 'Supplement Type', y = 'Mean Growth', title = 'Average effect of diet on growth') +
  theme_classic()
## Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
## ℹ Please use `linewidth` instead.
## This warning is displayed once per session.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.

Assessing if we should consider interactions

### table 
table(growth$diet, growth$supplement)
##         
##          control agrimore supergain supersupp
##   barley       4        4         4         4
##   oats         4        4         4         4
##   wheat        4        4         4         4

Constructing the model

### Constructing a linear model testing how diet, supplement and the interaction 
### of diet and supplement affect gain

model_cow <- lm(gain ~ diet * supplement, data = growth)

### Checking the assumptions of the linear model
autoplot(model_cow, smooth.colour =NA)
## Warning: `fortify(<lm>)` was deprecated in ggplot2 4.0.0.
## ℹ Please use `broom::augment(<lm>)` instead.
## ℹ The deprecated feature was likely used in the ggfortify package.
##   Please report the issue at <https://github.com/sinhrks/ggfortify/issues>.
## This warning is displayed once per session.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
## Warning: Removed 48 rows containing missing values or values outside the scale range
## (`geom_line()`).
## Removed 48 rows containing missing values or values outside the scale range
## (`geom_line()`).

### The autoplot highlights no pattern in the residuals vs fitted and scale-location
### map. The residuals vs leverage figure does not highlight any significant deviation
### however the QQplot highlights sample negative residuals that are smaller than ideal 

Running the ANOVA and visualizing the data

### Creating the two way ANOVA table based on the linear model
anova(model_cow)
## Analysis of Variance Table
## 
## Response: gain
##                 Df  Sum Sq Mean Sq F value    Pr(>F)    
## diet             2 287.171 143.586 83.5201 2.999e-14 ***
## supplement       3  91.881  30.627 17.8150 2.952e-07 ***
## diet:supplement  6   3.406   0.568  0.3302    0.9166    
## Residuals       36  61.890   1.719                      
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
### From assessing the output of this ANOVA table we can see that the interaction between diet and supplement on the growth of the cows is non-signficant, unlike diet, and supplement by itself 

sumMoo <- growth %>%
  group_by(diet, supplement) %>%
  summarise(meanGrow = mean (gain),
            seGrow = sd(gain)/sqrt(n())
  )
## `summarise()` has regrouped the output.
## ℹ Summaries were computed grouped by diet and supplement.
## ℹ Output is grouped by diet.
## ℹ Use `summarise(.groups = "drop_last")` to silence this message.
## ℹ Use `summarise(.by = c(diet, supplement))` for per-operation grouping
##   (`?dplyr::dplyr_by`) instead.
### Revisualization of previous means with line connecting them, also with standard
### error lines 
ggplot(sumMoo, aes(x = supplement, y = meanGrow, colour = diet, group = diet)) + 
  geom_point(shape = 21, size = 2, colour = 'black') +
  geom_line(size = 0.5) +
  geom_errorbar(aes(ymin = meanGrow - seGrow,
                ymax = meanGrow + seGrow), width = 0.1) +
  labs(x = 'Supplement Type', y = 'Mean Growth', title = 'Average effect of diet on growth') +
  theme_classic()

Preliminary viewing of data

### Importing relevant csv
limp <- read.csv("~/Desktop/Year 5/BIO4259A/datasets-master/limpet.csv")


### looking at the variables in the data
glimpse(limp)
## Rows: 24
## Columns: 3
## $ DENSITY <int> 8, 8, 8, 8, 8, 8, 15, 15, 15, 15, 15, 15, 30, 30, 30, 30, 30, …
## $ SEASON  <chr> "spring", "spring", "spring", "summer", "summer", "summer", "s…
## $ EGGS    <dbl> 2.875, 2.625, 1.750, 2.125, 1.500, 1.875, 2.600, 1.866, 2.066,…
### changing SEASON to a factor
limp <- mutate(limp, SEASON = as.factor(SEASON))

### successfully changed to a factor
glimpse(limp)
## Rows: 24
## Columns: 3
## $ DENSITY <int> 8, 8, 8, 8, 8, 8, 15, 15, 15, 15, 15, 15, 30, 30, 30, 30, 30, …
## $ SEASON  <fct> spring, spring, spring, summer, summer, summer, spring, spring…
## $ EGGS    <dbl> 2.875, 2.625, 1.750, 2.125, 1.500, 1.875, 2.600, 1.866, 2.066,…
### Visualization of the data 
ggplot(limp, aes(x = DENSITY, y = EGGS, colour = SEASON)) +
  geom_point() +
  scale_color_manual(values = c(spring="green", summer="red")) +
  theme_bw()

### constructing linear model assessing the effects of season, density and their 
### interaction on egg production 
limp.mod <- lm(EGGS ~ DENSITY * SEASON, data = limp)


### Checking the assumptions of the model
autoplot(limp.mod, smooth.colour = NA)
## Warning: Removed 24 rows containing missing values or values outside the scale range
## (`geom_line()`).
## Removed 24 rows containing missing values or values outside the scale range
## (`geom_line()`).
## Removed 24 rows containing missing values or values outside the scale range
## (`geom_line()`).

### We can observe a lack of pattern in the scale-location graph and in the residuals
### vs fitted

### Running an anova on the model, here we can see a lack of significant interaction 
### between density and season
anova(limp.mod) 
## Analysis of Variance Table
## 
## Response: EGGS
##                Df Sum Sq Mean Sq F value    Pr(>F)    
## DENSITY         1 5.0241  5.0241 30.1971 2.226e-05 ***
## SEASON          1 3.2502  3.2502 19.5350 0.0002637 ***
## DENSITY:SEASON  1 0.0118  0.0118  0.0711 0.7925333    
## Residuals      20 3.3275  0.1664                      
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
### Looking at the summary table we can be informed of the coefficiants which informs
### us of the equation showing the relationsgip between eggs, season and density
summary(limp.mod) 
## 
## Call:
## lm(formula = EGGS ~ DENSITY * SEASON, data = limp)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -0.65468 -0.25021 -0.03318  0.28335  0.57532 
## 
## Coefficients:
##                       Estimate Std. Error t value Pr(>|t|)    
## (Intercept)           2.664166   0.234118  11.380 3.45e-10 ***
## DENSITY              -0.033650   0.008259  -4.074 0.000591 ***
## SEASONsummer         -0.812282   0.331092  -2.453 0.023450 *  
## DENSITY:SEASONsummer  0.003114   0.011680   0.267 0.792533    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 0.4079 on 20 degrees of freedom
## Multiple R-squared:  0.7135, Adjusted R-squared:  0.6705 
## F-statistic:  16.6 on 3 and 20 DF,  p-value: 1.186e-05

Visualizing the limpet dataset

### Creating a reference grid to be used later with predict() to draw regression lines 
new.x <- expand.grid(
  DENSITY = seq(from = 8, to = 45, length.out = 10),
  SEASON = levels(limp$SEASON))

### The predict function will generate fitted values based on the limpet model 
new.y <- predict(limp.mod, newdata = new.x, interval = 'confidence')


### Here we establish the dataframe to bring together the new.x and new.y objects
addThese <- data.frame(new.x, new.y)
### renaming fit variable to EGGS 
addThese<-rename(addThese, EGGS = fit)

### Final visualization which incorperates a line and confidence intervals into the 
### graph
ggplot(limp, aes(x = DENSITY, y = EGGS, colour = SEASON)) +
  geom_point(size = 3) +
  geom_smooth(data = addThese,
    aes(ymin = lwr, ymax = upr, fill = SEASON),
    stat = 'identity') +
  labs(x = "Density", y = 'Egg Production', title = "Seasonal Egg Production due to Season") +
scale_colour_manual(values = c(spring="green",
summer="red")) +
scale_fill_manual(values = c(spring="green",
summer="red")) +
theme_bw()