The library() function will be used to load the packages
needed for data manipulation, graph creation and model diagnostics. The
read.csv() function will be used to import the cow growth
dataset and assign it to an object called growth.
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(ggplot2)
library(ggfortify)
growth <- read.csv("/Users/harleen/Desktop/Biostatistics/data/growth.csv")
The packages were successfully loaded and the growth dataset was
imported into an object called growth.
The dim() function will be used to determine the number
of rows and columns in the dataset. The glimpse() function
will be used to examine the variable names and data types. The
colSums() and is.na() functions will be used
to identify any missing values in the dataset.
dim(growth)
## [1] 48 3
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,…
colSums(is.na(growth))
## supplement diet gain
## 0 0 0
The output provides information about the dimensions, variable types and missing values in the dataset. This allows the structure and completeness of the data to be examined before conducting the analysis.
The mutate() function will be used to convert the
supplement and diet variables into factors
because they represent categorical treatment groups. The
relevel() function will be used to set the control
supplement as the reference level.
growth <- growth %>%
mutate(
supplement = as.factor(supplement),
diet = as.factor(diet),
supplement = relevel(supplement, ref = "control")
)
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] "control" "agrimore" "supergain" "supersupp"
levels(growth$diet)
## [1] "barley" "oats" "wheat"
The output confirms that the supplement and diet variables have been converted into factors. The control supplement is now the reference level for the analysis.
A boxplot will be created to examine the distribution of cow weight
gain across the different supplement and diet treatment groups. The
geom_boxplot() function will display the median,
interquartile range and potential outliers within each group. This will
help identify unusual observations and compare the variation between
treatment groups.
ggplot(growth, aes(x = supplement, y = gain, fill = diet)) +
geom_boxplot(width = 0.65, alpha = 0.85) +
labs(
title = "Cow Weight Gain Across Treatment Groups",
x = "Supplement Type",
y = "Weight Gain",
fill = "Diet"
) +
theme_bw() +
theme(
plot.title = element_text(face = "bold", hjust = 0.5),
axis.title = element_text(face = "bold"),
legend.title = element_text(face = "bold")
)
The boxplot shows differences in cow weight gain across the supplement and diet combinations. A small number of observations are identified as potential outliers. However, these observations will not automatically be removed because they may represent genuine variation in the data.
The group_by() function will be used to group the
observations according to supplement and diet. The
summarize() function will then calculate the mean weight
gain for each treatment combination. The standard error will also be
calculated using the standard deviation divided by the square root of
the number of non-missing observations.
sumGrowth <- growth %>%
group_by(supplement, diet) %>%
summarize(
meanGrow = mean(gain, na.rm = TRUE),
seGrow = sd(gain, na.rm = TRUE) / sqrt(sum(!is.na(gain))),
.groups = "drop"
)
sumGrowth
## # A tibble: 12 × 4
## supplement diet meanGrow seGrow
## <fct> <fct> <dbl> <dbl>
## 1 control barley 23.3 0.703
## 2 control oats 20.5 0.506
## 3 control wheat 17.4 0.460
## 4 agrimore barley 26.3 0.919
## 5 agrimore oats 23.3 0.613
## 6 agrimore wheat 19.6 0.710
## 7 supergain barley 22.5 0.771
## 8 supergain oats 19.7 0.349
## 9 supergain wheat 17.0 0.485
## 10 supersupp barley 25.6 1.06
## 11 supersupp oats 21.9 0.413
## 12 supersupp wheat 19.7 0.475
The output displays the mean weight gain and standard error for each supplement and diet combination. These values will be used to create plots comparing the treatment groups.
A scatterplot will be created to display the mean cow weight gain
across the different supplement types. The ggplot()
function will specify supplement type as the x-axis and mean weight gain
as the y-axis. The geom_point() function will display the
mean values as points.
ggplot(sumGrowth, aes(x = supplement, y = meanGrow)) +
geom_point(size = 4, colour = "deeppink") +
labs(
title = "Mean Cow Weight Gain by Supplement",
x = "Supplement Type",
y = "Mean Weight Gain"
) +
theme_bw() +
theme(
plot.title = element_text(face = "bold", hjust = 0.5),
axis.title = element_text(face = "bold")
)
The scatterplot displays the mean weight gain for each diet and supplement combination. The points indicate that mean weight gain varies across the supplement treatments.
An interaction plot will be created to compare the mean weight gain
across supplement types for each diet. The geom_line()
function will connect the mean values within each diet, while
geom_point() will display the individual means. Different
colours will be used to distinguish the diets.
ggplot(sumGrowth, aes(
x = supplement,
y = meanGrow,
colour = diet,
group = diet
)) +
geom_line(linewidth = 1.2) +
geom_point(size = 3.5) +
scale_colour_manual(values = c(
"barley" = "coral",
"oats" = "lightgreen",
"wheat" = "cornflowerblue"
)) +
labs(
title = "Effect of Diet and Supplement on Cow Weight Gain",
x = "Supplement Type",
y = "Mean Weight Gain",
colour = "Diet"
) +
theme_bw() +
theme(
plot.title = element_text(face = "bold", hjust = 0.5),
axis.title = element_text(face = "bold"),
legend.title = element_text(face = "bold")
)
The interaction plot shows that barley consistently has the highest mean weight gain, followed by oats and wheat. The lines also show how the effect of supplement type varies across the diets. The statistical analysis will determine whether there is a significant interaction between diet and supplement.
The lm() function will be used to create a two-way ANOVA
model to investigate whether diet, supplement or their interaction
affect cow weight gain. The * operator includes both main
effects and the interaction between the two explanatory variables.
model_cow <- lm(gain ~ diet * supplement, data = growth)
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)
##
## 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
The ANOVA table displays the statistical results for diet, supplement and their interaction. The p-values will be used to determine whether these variables have statistically significant effects on cow weight gain. The model summary provides additional information about the estimated coefficients.
The autoplot() function from the ggfortify
package will be used to create diagnostic plots for the fitted ANOVA
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: 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()`).
The diagnostic plots show that the model is not a bad fit to the data.
A final interaction plot will be created to display mean cow weight
gain across the supplement and diet treatment groups, including standard
error bars. The geom_errorbar() function will be used to
display one standard error above and below each mean.
ggplot(sumGrowth, aes(
x = supplement,
y = meanGrow,
colour = diet,
group = diet
)) +
geom_line(linewidth = 1.2) +
geom_point(size = 3.5) +
geom_errorbar(
aes(
ymin = meanGrow - seGrow,
ymax = meanGrow + seGrow
),
width = 0.15,
linewidth = 0.8
) +
scale_colour_manual(values = c(
"barley" = "coral",
"oats" = "lightgreen",
"wheat" = "skyblue"
)) +
labs(
title = "Mean Cow Weight Gain Across Treatments",
subtitle = "Error bars represent ±1 standard error",
x = "Supplement Type",
y = "Mean Weight Gain",
colour = "Diet"
) +
theme_bw() +
theme(
plot.title = element_text(face = "bold", hjust = 0.5),
axis.title = element_text(face = "bold"),
legend.title = element_text(face = "bold")
)
The plot displays the mean weight gain for each treatment combination with error bars representing one standard error. The graph allows the variation and differences in mean weight gain between treatment groups to be compared.
The read.csv() function will be used to import the
limpet dataset and assign it to an object called limp. The
glimpse() function will be used to examine the dataset.
limp <- read.csv("/Users/harleen/Desktop/Biostatistics/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,…
The output shows that data was not imported correctly and that season needs to be converted into a factor.
The mutate() function will be used to convert the
SEASON variable into a factor.
limp <- limp %>%
mutate(SEASON = as.factor(SEASON))
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,…
levels(limp$SEASON)
## [1] "spring" "summer"
The output confirms that the season variable has been converted into a factor. The dataset contains spring and summer observations.
A boxplot will be created to examine the distribution of egg
production across the two seasons. The geom_boxplot()
function will display the median, interquartile range and variation in
egg production within each season.
ggplot(limp, aes(x = SEASON, y = EGGS, fill = SEASON)) +
geom_boxplot(alpha = 0.8, width = 0.65) +
scale_fill_manual(values = c(
"spring" = "lightpink",
"summer" = "orchid"
)) +
labs(
title = "Limpet Egg Production Across Seasons",
x = "Season",
y = "Number of Eggs"
) +
theme_bw() +
theme(
plot.title = element_text(face = "bold", hjust = 0.5),
axis.title = element_text(face = "bold"),
legend.position = "none"
)
The boxplot shows that egg production is generally higher during spring than summer. There is also variation in egg production within each season.
A scatterplot will be created to examine the relationship between
limpet density and egg production. The geom_point()
function will display the individual observations, with different
colours used to distinguish between seasons.
ggplot(limp, aes(x = DENSITY, y = EGGS, colour = SEASON)) +
geom_point(size = 3, alpha = 0.7) +
scale_colour_manual(values = c(
"spring" = "lightpink",
"summer" = "orchid"
)) +
labs(
title = "Limpet Density and Egg Production",
x = "Density",
y = "Number of Eggs",
colour = "Season"
) +
theme_bw() +
theme(
plot.title = element_text(face = "bold", hjust = 0.5),
axis.title = element_text(face = "bold"),
legend.title = element_text(face = "bold")
)
The scatterplot displays the relationship between limpet density and egg production for both seasons. The observations show variation in egg production across density levels, with differences also apparent between spring and summer.
The lm() function will be used to fit an ANCOVA model to
investigate whether limpet density, season and their interaction affect
egg production.
limp.mod <- lm(EGGS ~ DENSITY * SEASON, data = limp)
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
The ANOVA table shows that the model explained approxiamtely 71.4% of the variation in egg production.
The autoplot() function will be used to generate
diagnostic plots for the ANCOVA 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()`).
The diagnostic plots show that the model is not a bad fit to the data.
The expand.grid() function will be used to create a new
dataset containing a range of density values for both seasons. The
predict() function will then calculate the predicted egg
production values and their confidence intervals using the fitted ANCOVA
model.
new.x <- expand.grid(
DENSITY = seq(8, 45, length.out = 10),
SEASON = levels(limp$SEASON)
)
new.y <- predict(
limp.mod,
newdata = new.x,
interval = "confidence"
)
addThese <- data.frame(new.x, new.y)
addThese <- rename(addThese, EGGS = fit)
addThese
## DENSITY SEASON EGGS lwr upr
## 1 8.00000 spring 2.3949692 2.01928490 2.7706536
## 2 12.11111 spring 2.2566318 1.93122963 2.5820340
## 3 16.22222 spring 2.1182943 1.83427371 2.4023150
## 4 20.33333 spring 1.9799569 1.72406204 2.2358517
## 5 24.44444 spring 1.8416194 1.59599790 2.0872409
## 6 28.55556 spring 1.7032820 1.44791752 1.9586464
## 7 32.66667 spring 1.5649445 1.28188025 1.8480088
## 8 36.77778 spring 1.4266071 1.10245731 1.7507568
## 9 40.88889 spring 1.2882696 0.91403164 1.6625076
## 10 45.00000 spring 1.1499321 0.71973644 1.5801279
## 11 8.00000 summer 1.6075953 1.23191098 1.9832797
## 12 12.11111 summer 1.4820581 1.15665594 1.8074603
## 13 16.22222 summer 1.3565209 1.07250026 1.6405415
## 14 20.33333 summer 1.2309837 0.97508882 1.4868785
## 15 24.44444 summer 1.1054464 0.85982493 1.3510680
## 16 28.55556 summer 0.9799092 0.72454478 1.2352737
## 17 32.66667 summer 0.8543720 0.57130775 1.1374363
## 18 36.77778 summer 0.7288348 0.40468504 1.0529845
## 19 40.88889 summer 0.6032976 0.22905961 0.9775355
## 20 45.00000 summer 0.4777604 0.04756465 0.9079561
The new dataset contains predicted egg production values for both seasons across the selected density range. The lower and upper confidence interval columns show the uncertainty around the predicted mean egg production.
The mean() function will be used to calculate the
average limpet density. The expand.grid() function will
create a dataset containing this average density for both seasons. The
predict() function will then calculate the predicted egg
production and confidence intervals at the average density.
new.x2 <- expand.grid(
DENSITY = mean(limp$DENSITY, na.rm = TRUE),
SEASON = levels(limp$SEASON)
)
predEgg <- predict(
limp.mod,
newdata = new.x2,
interval = "confidence"
)
EggAtMeanDens <- data.frame(new.x2, predEgg)
EggAtMeanDens
## DENSITY SEASON fit lwr upr
## 1 24.5 spring 1.83975 1.5941303 2.08537
## 2 24.5 summer 1.10375 0.8581303 1.34937
The output displays the predicted egg production for spring and summer at the average limpet density. The confidence intervals provide an estimate of the uncertainty around these predicted mean values.
A final scatterplot will be created to display the observed egg
production values and the predicted relationships between density and
egg production for each season. The geom_point() function
will display the observed data, while geom_smooth() with
stat = "identity" will display the predicted values and
confidence intervals calculated previously.
ggplot(limp, aes(x = DENSITY, y = EGGS, colour = SEASON)) +
geom_point(size = 3, alpha = 0.65) +
geom_smooth(
data = addThese,
aes(
x = DENSITY,
y = EGGS,
ymin = lwr,
ymax = upr,
fill = SEASON,
group = SEASON
),
stat = "identity",
alpha = 0.2,
linewidth = 1
) +
scale_colour_manual(values = c(
"spring" = "lightpink",
"summer" = "orchid"
)) +
scale_fill_manual(values = c(
"spring" = "lightpink",
"summer" = "orchid"
)) +
labs(
title = "Limpet Egg Production Across Density Levels",
x = "Density",
y = "Number of Eggs",
colour = "Season",
fill = "Season"
) +
theme_bw() +
theme(
plot.title = element_text(face = "bold", hjust = 0.5),
axis.title = element_text(face = "bold"),
legend.title = element_text(face = "bold")
)
The plot displays the observed egg production values and the predicted relationships between density and egg production for spring and summer. The shaded areas represent the 95% confidence intervals around the predicted mean values.