I used library() to load necessary libraries dplyr, ggfortify and tidyverse so I can use their functions later:
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)
## Loading required package: ggplot2
library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ forcats 1.0.1 ✔ stringr 1.6.0
## ✔ lubridate 1.9.5 ✔ tibble 3.3.1
## ✔ purrr 1.2.2 ✔ tidyr 1.3.2
## ✔ readr 2.2.0
## ── 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
First I imported the data file growth.csv using read.csv() and using glimpse() to explore the data and check its structure:
growth.moo <-read.csv("/Users/isabel/Documents/Bio4259/Analyses/Biost_GettingStarted_withR/Data/growth.csv")
glimpse (growth.moo)
## 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,…
From using glimpse(), I noticed that the data I imported put supplement and diet as text (chr) unlike the demo showing them as factors (fctr) in Chapter 6 Beckerman. When I tried to download the growth.csv file they gave in the textbook, the link showed up as an error. So I will have to manually convert these two columns into factors using the factor function:
growth.moo <- growth.moo |>
mutate(
supplement = factor(supplement),
diet = factor(diet)
)
I checked the data structure again using glimpse(), which showed that supplement and diet have become factors (fct). Then I used levels() to see the levels associated with a factor, and used $ to grab information from the columns diet and supplement:
glimpse (growth.moo)
## 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.moo$diet)
## [1] "barley" "oats" "wheat"
levels (growth.moo$supplement)
## [1] "agrimore" "control" "supergain" "supersupp"
I then used relevel() with mutate() to make the control into the new reference by reordering the factor. I double checked to make sure it worked by using the levels function to ensure control was the first and not agrimore:
growth.moo <-
mutate(growth.moo,
supplement = relevel(supplement, ref="control"))
levels(growth.moo$supplement)
## [1] "control" "agrimore" "supergain" "supersupp"
First, I used sumMoo to store the new summary table of the mean for each combination of diet and supplement. I used a pipeline with group_by() to group the data by diet and supplement. Then I used summarise() to calculate the mean gain for each group. I also double checked it worked by typing sumMoo to show the summary table stored in the object.
sumMoo <- growth.moo %>%
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.
sumMoo
## # A tibble: 12 × 3
## # Groups: diet [3]
## diet supplement meanGrow
## <fct> <fct> <dbl>
## 1 barley control 23.3
## 2 barley agrimore 26.3
## 3 barley supergain 22.5
## 4 barley supersupp 25.6
## 5 oats control 20.5
## 6 oats agrimore 23.3
## 7 oats supergain 19.7
## 8 oats supersupp 21.9
## 9 wheat control 17.4
## 10 wheat agrimore 19.6
## 11 wheat supergain 17.0
## 12 wheat supersupp 19.7
I used ggplot() to create a plot from sumMoo. Inside aes(), I placed supplement on the x-axis and meanGrow on the y-axis. I used colour = diet to assign each diet a different colour, and group = diet to group the points by diet. The function geom_point() shows the mean gain for each combination, and geom_line() connects the points for each diet. I used labs to give it a title and x and y axes labels.I also adjusted the visuals of the plot by using scale_colour_brewer() and geom_point to adjust the size of the points. Finally, I used theme_bw() to give the plot a black and white background.
ggplot(sumMoo, aes(supplement, meanGrow, colour = diet, group = diet)) +
geom_point() +
geom_line( linewidth = 0.8) +
labs(
title = "The Mean Cow Weight Gain Across Diet and Supplement Types",
x = "Supplement Type",
y = "Mean Weight Gain",
colour = "Diet"
) +
scale_colour_brewer(palette="Dark2") +
geom_point(size = 4) +
theme_bw()
Null Hypothesis: The effect of supplement type on cow weight gain does not depend on diet
Alternative Hypothesis: The effect of supplement on cow weight gain depends on diet
To test which model hypothesis will work, I built a two-way ANOVA model. First, I used lm() to fit a linear model and I will store this model in model_cow. I used diet*supplement to expand the combination of variables to read as diet + supplement + diet:supplement, so that I can examine the effects of diet and supplement separately and together.
Then, I used autoplot() to create diagnostic plots for model_cow to check whether a statistical model fit the data. Smooth.colour = NA removed smoothed trend lines from the plots, so I could look for patterns in residuals and points that stood out:
model_cow <- lm(gain ~ diet * supplement, data = growth.moo)
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: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
## ℹ Please use `linewidth` 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()`).
To further analyse the linear model I’ll use anova() and summary(). The function anova will produce an ANOVA table giving sum of squares, mean squares, F-values and p-values. Summary function will give a table of coefficients, standard errors and t-values.
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
summary (model_cow)
##
## Call:
## lm(formula = gain ~ diet * supplement, data = growth.moo)
##
## Residuals:
## Min 1Q Median 3Q Max
## -2.48756 -1.00368 -0.07452 1.03496 2.68069
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 23.2966499 0.6555863 35.536 < 2e-16 ***
## dietoats -2.8029851 0.9271390 -3.023 0.00459 **
## dietwheat -5.8911317 0.9271390 -6.354 2.34e-07 ***
## supplementagrimore 3.0518277 0.9271390 3.292 0.00224 **
## supplementsupergain -0.8305263 0.9271390 -0.896 0.37631
## supplementsupersupp 2.2786527 0.9271390 2.458 0.01893 *
## dietoats:supplementagrimore -0.2471088 1.3111726 -0.188 0.85157
## dietwheat:supplementagrimore -0.8182729 1.3111726 -0.624 0.53651
## dietoats:supplementsupergain -0.0001351 1.3111726 0.000 0.99992
## dietwheat:supplementsupergain 0.4374395 1.3111726 0.334 0.74060
## dietoats:supplementsupersupp -0.9120830 1.3111726 -0.696 0.49113
## dietwheat:supplementsupersupp -0.0158299 1.3111726 -0.012 0.99043
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 1.311 on 36 degrees of freedom
## Multiple R-squared: 0.8607, Adjusted R-squared: 0.8182
## F-statistic: 20.22 on 11 and 36 DF, p-value: 3.295e-12
ANOVA table reveals no evidence to support the presence of an interaction between diet and supplement (F = 0.33; df = 6, 36; p = 0.92).
To further understand the variation, I calculated the mean and SD of gain for all 12 combinations. I used a pipeline with group_by() to group the data by diet and supplement. Then, I used summarise() to calculate the mean gain and standard error for each combination. The standard error was calculated by dividing the standard deviation by the square root of the number of observations in each group.
sumMoo <- growth.moo %>%
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.
Added points, lines, and error bars to the figure from earlier. I used geom_errorbar() to extend each error bar one standard error below and above its mean. The ymin and ymax aesthetics set these limits, and width = 0.1 controls the width of the error bar caps. Each vertical line is centered on the mean.
ggplot(sumMoo, aes(x = supplement, y = meanGrow,
colour = diet, group = diet)) +
geom_point() +
geom_line(linewidth = 0.8) +
geom_errorbar(aes(ymin = meanGrow - seGrow,
ymax = meanGrow + seGrow), width = 0.1) +
labs(
title = "The Mean Cow Weight Gain Across Diet and Supplement Types",
x = "Supplement Type",
y = "Mean Weight Gain",
colour = "Diet" ) +
scale_colour_brewer(palette="Dark2") +
geom_point(size = 4) +
theme_bw()
First I cleared my decks using rm(list=) and imported the libraries dyplyr, ggplot2 and ggfortify.
rm(list=ls())
library(dplyr)
library(ggplot2)
library(ggfortify)
I then imported the data using read.csv(). Then I used glimpse() to explore and see the data structure. From glimpse, I noticed that SEASON was not a factor so I will convert it from chr to factor using the factor function:
limp <-read.csv("/Users/isabel/Documents/Bio4259/Analyses/Biost_GettingStarted_withR/Data/limpet.csv")
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,…
limp$SEASON <- factor(limp$SEASON)
I used ggplot() to create a scatterplot from the limp data, mapping DENSITY to the x-axis, EGGS to the y-axis, and SEASON to point colour. I added the points with geom_point(), set spring points to green and summer points to red with scale_color_manual(), and applied a black-and-white theme with theme_bw(). I also gave the graph title and labels for the axes with the lab function.
Secondly I used the function lm() and assigned it to limp.mod. This will fit an ANCOVA model to observe how density, season and number of eggs interact with each other.
Then, I used autoplot() to create diagnostic plots for limp.mod to check whether a statistical model fit the data. Smooth.colour = NA removed smoothed trend lines from the plots, so I could look for patterns in residuals and points that stood out
Finally, I used names() to see the components listed inside limp.mod such as the coefficients and residuals:
ggplot(limp, aes(x = DENSITY, y = EGGS, colour = SEASON)) +
geom_point() +
scale_color_manual(values = c(spring="green", summer="red")) +
labs(
title = "Egg Count by Density and Season",
x = "Density",
y = "Egg count",
colour = "Season",
) +
theme_bw()
limp.mod <- lm(EGGS ~ DENSITY * SEASON, data = limp)
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()`).
names (limp.mod)
## [1] "coefficients" "residuals" "effects" "rank"
## [5] "fitted.values" "assign" "qr" "df.residual"
## [9] "contrasts" "xlevels" "call" "terms"
## [13] "model"
First, I used anova() to get an ANOVA table, which gives us the sum of squares, mean squares, F-values and p-values. Secondly, I used the summary function to get a table of coefficents, standard errors and t-values. This will be used to know the rate of density dependence:
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
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
ANOVA table results found no evidence for an interaction between density and season (F = 0.0711; df = 1,20; p = 0.79), indicating that the effects of density and season are additive.
Summary table shows no evidence that effect of density depends on season. Results align with ANOVA table’s information.
I added fitted lines and 95% confidence bands to the pre-existing scatter plot to further observe the relationship between density and egg count for each season:
I used the function expand.grid() to create every combination of the values and put them into a data frame. Then I used predict() to calculate predicted egg counts from the limp.mod model.
expand.grid(FIRST = c("A", "B"), SECOND = c(1, 2))
## FIRST SECOND
## 1 A 1
## 2 B 1
## 3 A 2
## 4 B 2
predict (limp.mod)
## 1 2 3 4 5 6 7 8
## 2.3949692 2.3949692 2.3949692 1.6075953 1.6075953 1.6075953 2.1594217 2.1594217
## 9 10 11 12 13 14 15 16
## 2.1594217 1.3938428 1.3938428 1.3938428 1.6546769 1.6546769 1.6546769 0.9358016
## 17 18 19 20 21 22 23 24
## 0.9358016 0.9358016 1.1499321 1.1499321 1.1499321 0.4777604 0.4777604 0.4777604
I then added SEASON to the grid using the functions level() and expand.grid() to extract information from SEASON column. I used head() to confirm the code worked:
new.x <- expand.grid(
DENSITY = seq(from = 8, to = 45, length.out = 10),
SEASON = levels(limp$SEASON))
head(new.x)
## DENSITY SEASON
## 1 8.00000 spring
## 2 12.11111 spring
## 3 16.22222 spring
## 4 20.33333 spring
## 5 24.44444 spring
## 6 28.55556 spring
I embedded the new xs into the function predict() using the newdata argument. I then assigned the new prediction to a new object called new.y, which is estimated using coeffs from the fitted model:
new.y <- predict(limp.mod, newdata=new.x,
interval = 'confidence')
head(new.y)
## fit lwr upr
## 1 2.394969 2.019285 2.770654
## 2 2.256632 1.931230 2.582034
## 3 2.118294 1.834274 2.402315
## 4 1.979957 1.724062 2.235852
## 5 1.841619 1.595998 2.087241
## 6 1.703282 1.447918 1.958646
I combined the new predictor values and predictors into a data frame and renamed fit to EGGS so it better matched.
I did this by first combining new density and season values in new.x with the predicted egg counts and confidence limits in new.y using data.frame(), storing the result in the object addThese. I then used rename() to change the predicted value column from fit to EGGS, matching the response variable name in the original data.
addThese <- data.frame(new.x, new.y)
addThese <- rename(addThese, EGGS = fit)
I used head (addThese) to check the first rows to ensure the code worked smoothly:
head(addThese)
## DENSITY SEASON EGGS lwr upr
## 1 8.00000 spring 2.394969 2.019285 2.770654
## 2 12.11111 spring 2.256632 1.931230 2.582034
## 3 16.22222 spring 2.118294 1.834274 2.402315
## 4 20.33333 spring 1.979957 1.724062 2.235852
## 5 24.44444 spring 1.841619 1.595998 2.087241
## 6 28.55556 spring 1.703282 1.447918 1.958646
I used ggplot() to create a scatterplot of egg count (EGGS) against density (DENSITY), with colour distinguishing the seasons. I added the observed data points using geom_point(), then used geom_smooth() with the predictions in the obejct addThese to display the fitted lines and confidence intervals for each season. I did theme_bw() applies a black and white theme. I also adjusted the sizing and width of the lines and points, along with the colour via scale_colour_manual, to make the graph look more visually appealing. Finally, I used labs(title=, x= and y=) to give the graph a title and labels for axes.
ggplot(limp, aes(x = DENSITY, y = EGGS, colour = SEASON)) +
geom_point(size = 5) +
geom_smooth(data = addThese,
aes(ymin = lwr, ymax = upr, fill = SEASON),
stat = "identity",
alpha = 0.2,
linewidth = 0.8) +
scale_colour_manual(values = c(spring="#E88AB8",
summer="#8FD3B6")) +
scale_fill_manual(values = c(spring="#E88AB8",
summer="#8FD3B6")) +
labs(
title = "Egg Count by Density and Season",
x = "Density",
y = "Egg count",
colour = "Season",
) +
theme_bw()