BCB744 (BioStatistics): Summative Task 2, 12 April 2024

Published

August 3, 2025

Honesty Pledge

This assignment requires that you work as an individual and not share your code, results, or discussion with your peers. Penalties and disciplinary action will apply if you are found cheating.

NoteAcknowledgement of the Pledge

Copy the statement, below, into your document and replace the underscores with your name acknowledging adherence to the UWC’s Honesty Pledge.

I, ____________, hereby state that I have not communicated with or gained information in any way from my peers and that all work is my own.

Instructions

Please note the following instructions. Failing to comply with them in full will result in a loss of marks.

  • QUARTO –> HTML Submit your assessment answers as an .html file compiled from your Quarto document. Produce fully annotated reports, including the meta-information at the top (name, date, purpose, etc.). Provide ample commentary explaining the purpose of the various tests/sections as necessary.

  • TESTING OF ASSUMPTIONS For all questions, make sure that when formal inferential statistics are required, each is preceded by the appropriate tests for the assumptions, i.e., state the assumptions, state the statistical procedure for testing the assumptions and mention their corresponding H0. If a graphical approach is used to test assumptions, explain the principle behind the approach. Explain the findings emerging from the test of assumptions, and justify your selection of the appropriate inferential test (e.g. t-test, ANOVA, etc.) that you will use.

  • STATE HYPOTHESES When inferential statistics are required, please provide the full H0 and HA, and conclude the analysis with a statement of which is accepted or rejected.

  • GRAPHICAL SUPPORT All descriptive and inferential statistics must be supported by the appropriate figures of the results.

  • STATEMENT OF RESULTS Make sure that the textual statement of the final result is written exactly as required for it to be published in a journal article. Please consult a journal if you don’t know how.

  • FORMATTING Pay attention to formatting. Some marks will be allocated to the appearance of the script, including considerations of aspects of the tidiness of the file, the use of the appropriate headings, and adherence to code conventions (e.g. spacing etc.).

  • MARK ALLOCATION Please see the Introduction Page for an explanation of the assessment approach that will be applied to these questions.

Submit the .html file wherein you provide answers to Questions 1–7 by no later than 19:00 today. Label the script as follows:

BCB744_<Name>_<Surname>_Summative_Task_2.html, e.g.

BCB744_AJ_Smit_Summative_Task_2.html.

Upload your .html files onto Google Forms.

Question 1

Chromosomal effects of mercury-contaminated fish consumption

These data reside in package coin, dataset mercuryfish. The dataframe contains the mercury level in blood, the proportion of cells with abnormalities, and the proportion of cells with chromosome aberrations in consumers of mercury-contaminated fish and a control group. Please see the dataset’s help file for more information.

Analyse the dataset and answer the following questions:

  1. Does the presence of methyl-mercury in a diet containing fish result in a higher proportion of cellular abnormalities?

  2. Does the concentration of mercury in the blood influence the proportion of cells with abnormalities, and does this differ between the control and exposed groups?

  3. Is there a relationship between the variables abnormal and ccells? This will have to be for the control and exposed groups, noting that an interaction effect might be present.

Answers

  1. Does the presence of methyl-mercury in a diet containing fish result in a higher proportion of cellular abnormalities?
library(coin)
data(mercuryfish)
head(mercuryfish)
    group mercury abnormal ccells
1 control     5.3      8.6    2.7
2 control    15.0      5.0    0.5
3 control    11.0      8.4    0.0
4 control     5.8      1.0    0.0
5 control    17.0     13.0    5.0
6 control     7.0      5.0    0.0
# EDA: do a boxplot
ggplot(mercuryfish, aes(x = group, y = abnormal)) +
  geom_boxplot(aes(colour = group), notch = TRUE)

# Looking at the above figure, we see that there is a statistically
# significant difference between the two groups. We will now test the
# assumption.

# Testing assumptions
# 1. Normality

# Shapiro-Wilk test
# H0: The data are normally distributed
# Ha: The data are not normally distributed

shapiro.test(mercuryfish$abnormal[mercuryfish$group == "control"])

    Shapiro-Wilk normality test

data:  mercuryfish$abnormal[mercuryfish$group == "control"]
W = 0.90267, p-value = 0.0887
shapiro.test(mercuryfish$abnormal[mercuryfish$group == "exposed"])

    Shapiro-Wilk normality test

data:  mercuryfish$abnormal[mercuryfish$group == "exposed"]
W = 0.96841, p-value = 0.6509
# We see that the data are normally distributed.

# Test homogeneity of variances

# Levene's test

# H0: The variances are equal
# Ha: The variances are not equal

car::leveneTest(abnormal ~ group, data = mercuryfish)
Levene's Test for Homogeneity of Variance (center = median)
      Df F value Pr(>F)
group  1  1.6607 0.2055
      37               
# We can therefore go ahead and perform the test.
# We select a Student's two sample t-test

t.test(abnormal ~ group, var.equal = TRUE, data = mercuryfish)

    Two Sample t-test

data:  abnormal by group
t = -2.9664, df = 37, p-value = 0.005253
alternative hypothesis: true difference in means between group control and group exposed is not equal to 0
95 percent confidence interval:
 -7.084765 -1.334257
sample estimates:
mean in group control mean in group exposed 
             4.668750              8.878261 
# We now have confirmation that the presence of methyl-mercury in a diet
# will have a significant effect on the proportion of cellular abnormalities.
  1. Does the concentration of mercury in the blood influence the proportion of cells with abnormalities, and does this differ between the control and exposed groups?
  # EDA: Scatterplot of mercury concentration vs. proportion of abnormal
  # cells
  
  ggplot(mercuryfish, aes(x = mercury, y = abnormal, color = group)) +
    geom_point() +
    geom_smooth(method = "lm", se = TRUE) +
    labs(title = "Mercury Concentration vs. Proportion of Abnormal Cells",
         x = "Mercury Concentration",
         y = "Proportion of Abnormal Cells")

  # Test normality of the data
  
  shapiro.test(mercuryfish$mercury[mercuryfish$group == "control"])

    Shapiro-Wilk normality test

data:  mercuryfish$mercury[mercuryfish$group == "control"]
W = 0.97435, p-value = 0.9032
  shapiro.test(mercuryfish$mercury[mercuryfish$group == "exposed"])

    Shapiro-Wilk normality test

data:  mercuryfish$mercury[mercuryfish$group == "exposed"]
W = 0.64984, p-value = 3.341e-06
  # We see that the mercury concentrations are normally distributed for the 
  # control group (we do not reject H0) but not for the exposed group
  # (we reject H0); earlier we have seen that the response variable
  # (abnormalities) is normal for both the control and the exposed groups
  
  # But since we want to model a linear relationship, now is not quite the
  # right time to do the tests for normality -- we want to do this for the
  # residuals of the model (that is, we fit the model first, and then test 
  # the residuals for normality)
  
  # We also see from the scatterplot that the data might be approximately
  # linear for the exposed group, but not for the control group where the
  # data are more scattered around very low mercury concentrations near
  # zero
   
  # We also see from the very wide confidence inrtervals that the model is
  # not very good at predicting the proportion of abnormal cells from
  # mercury concentration in the blood in the exposed group; my guess is
  # that there will not be a linear relationship between mercury
  # concentration and the proportion of abnormal cells in the control or
  # exposed groups
   
  # We can proceed with a linear regression model to assess the
  # relationship
  
  # Fit a linear regression model to assess the relationship between
  # mercury concentration and the proportion of abnormal cells
  # H0(1): There is no relationship between mercury concentration and the
  # proportion of abnormal cells
  # Ha(1): There is a relationship between mercury concentration and the
  # proportion of abnormal cells
  # H0(2): The relationship between mercury concentration and the
  # proportion of abnormal cells does not differ between the control and
  # exposed groups
  # Ha(2): The relationship between mercury concentration and the
  # proportion of abnormal cells differs between the control and exposed
  # groups
  
  model.lm <- lm(abnormal ~ mercury * group, data = mercuryfish)
  summary(model.lm)

Call:
lm(formula = abnormal ~ mercury * group, data = mercuryfish)

Residuals:
   Min     1Q Median     3Q    Max 
-8.183 -2.475 -0.512  2.639 13.328 

Coefficients:
                     Estimate Std. Error t value Pr(>|t|)  
(Intercept)            0.8227     2.7536   0.299   0.7669  
mercury                0.4303     0.2842   1.514   0.1390  
groupexposed           7.0434     3.0027   2.346   0.0248 *
mercury:groupexposed  -0.4252     0.2842  -1.496   0.1436  
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 4.253 on 35 degrees of freedom
Multiple R-squared:  0.2727,    Adjusted R-squared:  0.2103 
F-statistic: 4.373 on 3 and 35 DF,  p-value: 0.01023
  # We can now check the residuals for normality in the two groups
  # which will confirm that the model is appropriate (or not)
  
  mercuryfish$residuals <- residuals(model.lm)
  shapiro.test(mercuryfish$residuals[mercuryfish$group == "control"])

    Shapiro-Wilk normality test

data:  mercuryfish$residuals[mercuryfish$group == "control"]
W = 0.95337, p-value = 0.5449
  shapiro.test(mercuryfish$residuals[mercuryfish$group == "exposed"])

    Shapiro-Wilk normality test

data:  mercuryfish$residuals[mercuryfish$group == "exposed"]
W = 0.94975, p-value = 0.2892
  # We see that the residuals are normally distributed for both groups
  # and hence using a linear model was appropriate

  # The p-value for the interaction term not less than 0.05, indicating
  # that the relationship between mercury concentration and the proportion
  # of abnormal cells does not differ between the control and exposed
  # groups -- we can reject Ha(1) and Ha(2)
  # If we wanted to (recommended), we could refit the model without the 
  # interaction term
  
    
  # What do we conclude?
  # The proportion of abnormal cells differs significantly between the
  # control and exposed groups, with the exposed group exhibiting a higher
  # proportion of abnormal cells. However, the relationship between mercury
  # concentration and the proportion of abnormal cells does not differ
  # between the two groups.
  # There is a good amount of scatter in the amount of cell abnormalities
  # even in just the control group, which suggests that mercury
  # concentration alone may not be a strong predictor of cellular
  # abnormalities. Increasing the amount of mercury in the blood does not
  # necessarily lead to a linear increase but it certainly does account
  # for a few of the highest values seen in the exposed group.
  1. Relationship Between Variables
  # EDA: Scatterplot of mercury concentration vs. age
  
  ggplot(mercuryfish, aes(x = abnormal, y = ccells, color = group)) +
    geom_point() +
    geom_smooth(method = "lm", se = TRUE) +
    labs(title = "Mercury Concentration vs. Age",
         x = "Proportion of Abnormal Cells",
         y = "Proportion of Cu cells")

  # We see that there is a clear linear relationship between abnormal cell
  # proportion and Cu cell proportion in both groups, and the confidence
  # intervals are narrow(-ish), indicating that the model could be
  # reasonably good at predicting Cu cell proportion from the proportion of
  # abnormal cells
  
  # We know the relationship between continuous covariates is linear and
  # may therefore proceed with a linear regression model; the remaining
  # assumptions will be tested afterwards
  
  # Fit a linear regression model to assess the relationship between the 
  # proportion of Cu cells and the proportion of abnormal cells
  # H0(1): There is no relationship between the proportion of Cu cells and
  # the proportion of abnormal cells
  # Ha(1): There is a relationship between the proportion of Cu cells and
  # the proportion of abnormal cells
  # H0(2): The relationship between the proportion of Cu cells and the
  # proportion of abnormal cells does not differ between the control and
  # exposed groups
  # Ha(2): The relationship between the proportion of Cu cells and the
  # proportion of abnormal cells differs between the control and exposed
  # groups
  
  model.lm2 <- lm(ccells ~ abnormal + group, data = mercuryfish)
  summary(model.lm2)

Call:
lm(formula = ccells ~ abnormal + group, data = mercuryfish)

Residuals:
    Min      1Q  Median      3Q     Max 
-2.4760 -0.7479  0.1761  0.5831  2.0133 

Coefficients:
             Estimate Std. Error t value Pr(>|t|)    
(Intercept)  -0.67797    0.36166  -1.875    0.069 .  
abnormal      0.37547    0.04461   8.417 5.01e-10 ***
groupexposed  0.12272    0.42837   0.286    0.776    
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 1.183 on 36 degrees of freedom
Multiple R-squared:  0.7152,    Adjusted R-squared:  0.6994 
F-statistic: 45.21 on 2 and 36 DF,  p-value: 1.516e-10
  # We can now check the residuals for normality in the two groups
  # which will confirm that the model is appropriate (or not)
  
  mercuryfish$residuals2 <- residuals(model.lm2)
  shapiro.test(mercuryfish$residuals2[mercuryfish$group == "control"])

    Shapiro-Wilk normality test

data:  mercuryfish$residuals2[mercuryfish$group == "control"]
W = 0.95476, p-value = 0.5686
  shapiro.test(mercuryfish$residuals2[mercuryfish$group == "exposed"])

    Shapiro-Wilk normality test

data:  mercuryfish$residuals2[mercuryfish$group == "exposed"]
W = 0.96346, p-value = 0.5366
  # We see that the residuals are normally distributed for both groups
  # and hence using a linear model was appropriate

  # The p-value 'abnormal' term is less than 0.05, indicating that the
  # relationship between the proportion of abnormal cells and the
  # proportion of Cu cells is significant -- we accept Ha(1)
  # The p-value for the interaction term is not less than 0.05, indicating
  # that the relationship between the proportion of abnormal cells and the
  # proportion of Cu cells does not differ between the control and exposed
  # groups -- we do not reject H0(2)
    
  # What do we conclude?
  # The proportion of Cu cells is significantly related to the proportion
  # of abnormal cells, with a higher proportion of abnormal cells
  # corresponding to a higher proportion of Cu cells. This relationship
  # does not differ between the control and exposed groups. The model is
  # appropriate for predicting the proportion of Cu cells from the
  # proportion of abnormal cells, as the residuals are normally distributed
  # for both groups.
  
  # Alternative approaches for assigning marks: Instead of doing a linear
  # regression with interaction term, which I did not formally teach,
  # equally justified are individual linear regressions for each group
  # and using the confidence intervals to make inferences. This would
  # involve fitting two linear regression models, one for each group, and
  # comparing the confidence intervals of the coefficients to determine if
  # the relationship between the proportion of Cu cells and the proportion
  # of abnormal cells differs between the two groups. This would apply to
  # all the other questions as well.
  
  # Or, in part (c), we could have done correlations for each group and
  # compared the correlation coefficients to determine if the relationship
  # between the proportion of abnormal cells and the proportion of Cu cells
  # differs between the two groups.

Question 2

Malignant glioma pilot study

Package coin, dataset glioma: A non-randomized pilot study on malignant glioma patients with pretargeted adjuvant radioimmunotherapy using yttrium-90-biotin.

  1. Do sex and group interact to affect survival time (time)?
  # Load the glioma dataset
  data(glioma, package = "coin")
  
  # Check the structure of the dataset
  str(glioma)
'data.frame':   37 obs. of  7 variables:
 $ no.      : int  1 2 3 4 5 6 7 8 9 10 ...
 $ age      : int  41 45 48 54 40 31 53 49 36 52 ...
 $ sex      : Factor w/ 2 levels "Female","Male": 1 1 2 2 1 2 2 2 2 2 ...
 $ histology: Factor w/ 2 levels "GBM","Grade3": 2 2 2 2 2 2 2 2 2 2 ...
 $ group    : Factor w/ 2 levels "Control","RIT": 2 2 2 2 2 2 2 2 2 2 ...
 $ event    : logi  TRUE FALSE FALSE FALSE FALSE TRUE ...
 $ time     : int  53 28 69 58 54 25 51 61 57 57 ...
  # Summary statistics
  summary(glioma)
      no.              age            sex      histology      group   
 Min.   : 1.000   Min.   :19.00   Female:16   GBM   :20   Control:18  
 1st Qu.: 5.000   1st Qu.:40.00   Male  :21   Grade3:17   RIT    :19  
 Median :10.000   Median :47.00                                       
 Mean   : 9.757   Mean   :48.49                                       
 3rd Qu.:14.000   3rd Qu.:57.00                                       
 Max.   :19.000   Max.   :83.00                                       
   event              time      
 Mode :logical   Min.   : 5.00  
 FALSE:14        1st Qu.:13.00  
 TRUE :23        Median :28.00  
                 Mean   :30.84  
                 3rd Qu.:50.00  
                 Max.   :69.00  
  # EDA: Boxplot of survival
  ggplot(glioma, aes(x = group, y = time)) +
    geom_boxplot(notch = FALSE, aes(colour = sex)) +
    labs(title = "Survival Time by Group",
       x = "Group",
       y = "Months")

  # There does seem to be an effect of group on survival time, with the 
  # radioimmunotherapy group having a higher median survival time
  # than the control group
  # A sex-related effect does not seem present
  
  # Looking at the box and whisker plot, there seems to be an issue with 
  # the assumption of normality. Let's test the normality of the data
  # using the Shapiro-Wilk test:
  
  # Shapiro-Wilk test for normality
  # H0: The data are normally distributed
  # Ha: The data are not normally distributed
  # (seperate hypotheses for sex and group))
  
  shapiro.test(glioma$tim[glioma$group == "Control"])

    Shapiro-Wilk normality test

data:  glioma$tim[glioma$group == "Control"]
W = 0.80087, p-value = 0.001563
  shapiro.test(glioma$tim[glioma$group == "RIT"])

    Shapiro-Wilk normality test

data:  glioma$tim[glioma$group == "RIT"]
W = 0.92571, p-value = 0.1443
  shapiro.test(glioma$tim[glioma$sex == "Female"])

    Shapiro-Wilk normality test

data:  glioma$tim[glioma$sex == "Female"]
W = 0.87292, p-value = 0.03016
  shapiro.test(glioma$tim[glioma$sex == "Male"])

    Shapiro-Wilk normality test

data:  glioma$tim[glioma$sex == "Male"]
W = 0.90727, p-value = 0.04852
  # The p-values are less than 0.05 for the control group and for both
  # sexes, indicating that the data are not normally distributed. We will
  # use non-parametric tests to compare the survival times between the
  # two groups within the factors.
  
  # We must also check the homogeneity of variances using Levene's test:
  # H0: The variances are equal
  # Ha: The variances are not equal
  
  car::leveneTest(time ~ group, data = glioma)
Levene's Test for Homogeneity of Variance (center = median)
      Df F value Pr(>F)
group  1  1.5274 0.2247
      35               
  car::leveneTest(time ~ sex, data = glioma)
Levene's Test for Homogeneity of Variance (center = median)
      Df F value Pr(>F)
group  1  0.0069 0.9344
      35               
  # Variances are the same everywhere; nevertheless, due to the 
  # non-normal data, we will have to use a non-parametric test.
  
  # We will check for differences between groups formally using the
  # Kruskal-Wallis test:
  
  # Kruskal-Wallis test
  # H0: The medians of the groups are equal
  # Ha: At least one median is different
  # (to be stated separately for group and sex)
  
  kruskal.test(time ~ group, data = glioma)

    Kruskal-Wallis rank sum test

data:  time by group
Kruskal-Wallis chi-squared = 16.123, df = 1, p-value = 5.936e-05
  kruskal.test(time ~ sex, data = glioma)

    Kruskal-Wallis rank sum test

data:  time by sex
Kruskal-Wallis chi-squared = 0.54251, df = 1, p-value = 0.4614
  # The p-value is less than 0.05, indicating that there is a significant
  # difference in survival time between the two groups. We reject the null
  # hypothesis and conclude that the medians of the groups are not equal,
  # but we do not reject the H0 for sex differences.
  
  # We cannot do a formal stats test to look for significant interaction 
  # terms between sex and group due to the non-normality of the data (i.e.
  # there is not non-parametric equivalent for a two-way ANOVA); However, we
  # can simply look at the box-and-whisker plot: there does not seem to be
  # a significant interaction as the response is the same regardless of
  # sex within each group.
  1. Do age and histology interact to affect survival time (time)?
  # EDA: Line/scatterplot of survival by histology and age
  ggplot(glioma, aes(x = age, y = time)) +
    geom_point(aes(colour = histology)) +
    geom_smooth(method = "lm", se = TRUE, aes(colour = histology)) +
    labs(title = "Survival Time by Histology and Age",
       x = "Age (Years)",
       y = "Survival time (Months)")

  # There does not seem to be a clear effect of age on survival time
  # within each histology group. Notice the wide confidence intervals
  # at the starts and ends of the age range for each histology group:
  # the starts and ends overlap within each group suggesting a statistically
  # insignificant effect of age
  
  # We can test formally with a linear model:
   
  # Linear model
  # H0: There is no interaction between age and histology
  # Ha: There is an interaction between age and histology
  
  model.lm <- lm(time ~ age * histology, data = glioma)
  summary(model.lm)

Call:
lm(formula = time ~ age * histology, data = glioma)

Residuals:
    Min      1Q  Median      3Q     Max 
-37.830 -10.163  -1.397  10.392  37.274 

Coefficients:
                    Estimate Std. Error t value Pr(>|t|)   
(Intercept)          38.2531    13.7074   2.791  0.00867 **
age                  -0.3516     0.2461  -1.429  0.16239   
histologyGrade3      -3.2009    20.5856  -0.155  0.87738   
age:histologyGrade3   0.5739     0.4308   1.332  0.19194   
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 15.48 on 33 degrees of freedom
Multiple R-squared:  0.4464,    Adjusted R-squared:  0.396 
F-statistic: 8.869 on 3 and 33 DF,  p-value: 0.0001877
  # Before we can interpret the linear model fit, we must check that the lm
  # is indeed suited to the data. We can do this by checking the residuals:
  
  # Residuals vs Fitted plot
  plot(model.lm, which = 1)

  # Or you could check normality of residuals with a QQ plot:
  
  # Normal Q-Q plot
  
  qqnorm(model.lm$residuals)

  # Or you could check for homogeneity of variances with a residuals vs
  # fitted plot:
  
  # Residuals vs Fitted plot
  
  plot(model.lm, which = 3)

  # Or simply assess the normality of the residuals with a Shapiro-Wilk test:
  
  # Shapiro-Wilk test for normality
  
  glioma$residuals <- model.lm$residuals
  
  shapiro.test(glioma$residuals[glioma$group == "RIT"])

    Shapiro-Wilk normality test

data:  glioma$residuals[glioma$group == "RIT"]
W = 0.93321, p-value = 0.1984
  shapiro.test(glioma$residuals[glioma$group == "Control"])

    Shapiro-Wilk normality test

data:  glioma$residuals[glioma$group == "Control"]
W = 0.90444, p-value = 0.0687
  # Okay, residuals are normal according to most tests above.
  
  # The interaction term is not significant, indicating that there is no
  # interaction between age and histology on survival time.
  
  # We will use the Kruskal-Wallis test to compare survival times between
  # the different histology groups:
  
  # Kruskal-Wallis test
  # H0: The medians of the histology groups are equal
  # Ha: At least one median is different
  
  kruskal.test(time ~ histology, data = glioma)

    Kruskal-Wallis rank sum test

data:  time by histology
Kruskal-Wallis chi-squared = 13.74, df = 1, p-value = 0.0002099
  # The p-value is less than 0.05, indicating that there is a significant
  # difference in survival time between the histology groups. We reject the
  # null hypothesis and conclude that the medians of the histology groups
  # are not equal.
  
  # We cannot do a formal stats test to look for significant interaction
  # terms between age and histology due to the non-normality of the data;
  # However, we can simply look at the box-and-whisker plot: there does not
  # seem to be a significant interaction as the response is the same
  # regardless of age within each histology group.
  
  # Or we can test with an ANCOVA instead of the linear model above
  # (start first with the assumption of normality and variances
  # within the histology groups -- Levene's test and Shapiro-Wilk's test)
  
  model.aov1 <- aov(time ~ histology * age, data = glioma)
  summary(model.aov1)
              Df Sum Sq Mean Sq F value   Pr(>F)    
histology      1   5795    5795  24.169 2.36e-05 ***
age            1    159     159   0.662    0.422    
histology:age  1    425     425   1.775    0.192    
Residuals     33   7912     240                     
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
  # The outcome is the same as the linear model above: there is no
  # interaction between age and histology on survival time.
  1. Show a full graphical exploration of the data. Are there any other remaining patterns visible in the data that should be explored statistically? Study your results, select the most promising and insightful question that remains, and do the analysis.

Question 3

Risk factors associated with low infant birth weight

Package MASS, dataset birthwt: A dataset about the risk factors associated with low infant birth mass collected at Baystate Medical Center, Springfield, Mass. during 1986.

State three hypotheses and test them. Make sure one of the tests makes use of the 95% confidence interval approach rather than a formal inferential methodology.

# Load the birthwt dataset
library(MASS)
data(birthwt)

# Check the structure of the dataset
str(birthwt)
'data.frame':   189 obs. of  10 variables:
 $ low  : int  0 0 0 0 0 0 0 0 0 0 ...
 $ age  : int  19 33 20 21 18 21 22 17 29 26 ...
 $ lwt  : int  182 155 105 108 107 124 118 103 123 113 ...
 $ race : int  2 3 1 1 1 3 1 3 1 1 ...
 $ smoke: int  0 0 1 1 1 0 0 0 1 1 ...
 $ ptl  : int  0 0 0 0 0 0 0 0 0 0 ...
 $ ht   : int  0 0 0 0 0 0 0 0 0 0 ...
 $ ui   : int  1 0 0 1 1 0 0 0 0 0 ...
 $ ftv  : int  0 3 1 2 0 0 1 1 1 0 ...
 $ bwt  : int  2523 2551 2557 2594 2600 2622 2637 2637 2663 2665 ...

Question 4

The LungCapData.csv data

  1. Using the Lung Capacity data provided, please calculate the 95% CIs for the LungCap variable as a function of:

    • Gender

    • Smoke

    • Caesarean

lungs <- read.csv("../data/LungCapData.csv", sep = "\t")

library(rcompanion)

(gender_ci <- groupwiseMean(LungCap ~ Gender, data = lungs, conf = 0.95, digits = 3))
  Gender   n Mean Conf.level Trad.lower Trad.upper
1 female 358 7.41       0.95       7.14       7.67
2   male 367 8.31       0.95       8.03       8.58
(smoke_ci <- groupwiseMean(LungCap ~ Smoke, data = lungs, conf = 0.95, digits = 3))
  Smoke   n Mean Conf.level Trad.lower Trad.upper
1    no 648 7.77       0.95       7.56       7.98
2   yes  77 8.65       0.95       8.22       9.07
(caesarean_ci <- groupwiseMean(LungCap ~ Caesarean, data = lungs, conf = 0.95, digits = 3))
  Caesarean   n Mean Conf.level Trad.lower Trad.upper
1        no 561 7.83       0.95       7.61       8.05
2       yes 164 7.97       0.95       7.56       8.38
  1. Create a graph of the mean ± 95% CIs and determine if there are statistical differences in LungCap between the levels of Gender, Smoke, and Caesarean. Do the same using inferential statistics. Are your findings the same using these two approaches?
plt1 <- ggplot(gender_ci, aes(x = Gender, y = Mean)) +
  geom_point() +
  geom_errorbar(aes(ymin = Trad.lower, ymax = Trad.upper), width = 0.2) +
  ylab("Mean lung capacity")

plt2 <- ggplot(smoke_ci, aes(x = Smoke, y = Mean)) +
  geom_point() +
  geom_errorbar(aes(ymin = Trad.lower, ymax = Trad.upper), width = 0.2) +
  ylab("Mean lung capacity")

plt3 <- ggplot(caesarean_ci, aes(x = Caesarean, y = Mean)) +
  geom_point() +
  geom_errorbar(aes(ymin = Trad.lower, ymax = Trad.upper), width = 0.2) +
  ylab("Mean lung capacity")

ggarrange(plt1, plt2, plt3, ncol = 3, labels = "AUTO")

  1. Produce all the associated tests for assumptions—i.e. the assumptions to be met when deciding whether to use your choice of inferential test or its non-parametric counterpart.
two_assum <- function(x) {
  x_var <- var(x)
  x_norm <- as.numeric(shapiro.test(x)[2])
  result <- c(x_var, x_norm)
  return(result)
}

lungs %>%
  group_by(Gender) %>%
  summarise(LungCap_var = round(two_assum(LungCap)[1], 3),
            LungCap_norm = round(two_assum(LungCap)[2], 3))
# A tibble: 2 × 3
  Gender LungCap_var LungCap_norm
  <chr>        <dbl>        <dbl>
1 female        6.58        0.002
2 male          7.2         0.073
lungs %>%
  group_by(Smoke) %>%
  summarise(LungCap_var = round(two_assum(LungCap)[1], 3),
            LungCap_norm = round(two_assum(LungCap)[2], 3))
# A tibble: 2 × 3
  Smoke LungCap_var LungCap_norm
  <chr>       <dbl>        <dbl>
1 no           7.43        0.008
2 yes          3.54        0.622
lungs %>%
  group_by(Caesarean) %>%
  summarise(LungCap_var = round(two_assum(LungCap)[1], 3),
            LungCap_norm = round(two_assum(LungCap)[2], 3))
# A tibble: 2 × 3
  Caesarean LungCap_var LungCap_norm
  <chr>           <dbl>        <dbl>
1 no               7.13        0.004
2 yes              6.97        0.554
# It would be best to continue with a Wilcoxon test
  1. Create a combined tidy dataframe (observe tidy principles) with the estimates for the 95% CI for the LungCap data (LungCap as a function of Gender), estimated using both the traditional and bootstrapping approaches. Create a plot comprising two panels (one for the traditional estimates, one for the bootstrapped estimates) of the mean, median, scatter of raw data points, and the upper and lower 95% CI.
groupwiseMean(LungCap ~ Gender, data = lungs, conf = 0.95, digits = 3, normal = TRUE) |>
  pivot_longer(cols = Trad.lower:Normal.upper,
               names_to = "type", values_to = "CI") |>
  separate(col = type, into = c("type", "direction")) |>
  pivot_wider(names_from = direction, values_from = CI) |>
  ggplot(aes(x = Gender, y = Mean)) +
    geom_jitter(data = lungs, aes(x = Gender, y = LungCap, colour = Smoke),
                width = 0.1, alpha = 0.2) +
    geom_point(colour = "black") +
    geom_errorbar(aes(ymin = lower, ymax = upper),
                  width = 0.2, colour = "black") +
    geom_point(data = lungs, aes(x = Gender, y = median(LungCap)),
               colour = "red", shape = "X") +
    facet_wrap(~type) +
    ylab("Mean lung capacity")

  1. Undertake a statistical analysis that incorporates both the effect of Age and one of the categorical variables on LungCap. What new insight does this provide?
# focus only on males
lungs |>
  filter(Gender == "male") |>
  group_by(Smoke) |>
  summarise(LungCap_var = round(two_assum(LungCap)[1], 3),
            LungCap_norm = round(two_assum(LungCap)[2], 3))
# A tibble: 2 × 3
  Smoke LungCap_var LungCap_norm
  <chr>       <dbl>        <dbl>
1 no           7.52        0.132
2 yes          2.94        0.565
# above we see that within males, the subgroups based on whether or not
# they smoke are normally distributed in both instances

mod1 <- lm(LungCap ~ Smoke * Age, data = lungs[lungs$Gender == "male", ])
summary(mod1)

Call:
lm(formula = LungCap ~ Smoke * Age, data = lungs[lungs$Gender == 
    "male", ])

Residuals:
    Min      1Q  Median      3Q     Max 
-4.5903 -0.9875  0.0920  1.0286  3.7097 

Coefficients:
             Estimate Std. Error t value Pr(>|t|)    
(Intercept)   1.44681    0.25191   5.743 1.96e-08 ***
Smokeyes      2.57844    1.48497   1.736   0.0833 .  
Age           0.56613    0.01996  28.367  < 2e-16 ***
Smokeyes:Age -0.21021    0.09924  -2.118   0.0348 *  
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 1.484 on 363 degrees of freedom
Multiple R-squared:  0.6968,    Adjusted R-squared:  0.6943 
F-statistic: 278.1 on 3 and 363 DF,  p-value: < 2.2e-16
# lung capacity of males is affected by age (disregarding effect of smoke),
# lung capacity is not affected by smoke (disregarding effect of age), but
# there is a significant interaction between them, i.e. the effect of age
# is more pronounced in non-smoker than it is in smokers...

lungs[lungs$Gender == "male", ] |>
  ggplot(aes(x = Age, y = LungCap)) +
    geom_point() +
    geom_smooth(method = "lm") +
    facet_wrap(~Smoke)

# the figure shows the interaction effect: in non-smokers their lung capacity
# increases more rapidly with age, whereas in smokers, the development of lung
# capacity with age seems to be stunted.

Question 5

The air quality data

Package datasets, dataset airquality. These are daily air quality measurements in New York, May to September 1973. See the help file for details.

  1. Which two of the four response variables are best correlated with each other?

Question 6

The shells.csv data

This dataset contains measurements of shell widths and lengths of the left and right valves of two species of mussels, Aulacomya sp. and Choromytilus sp. Length and width measurements are presented in mm.

Fully analyse this dataset.

Question 7

The fertiliser_crop_data.csv data

The data represent an experiment designed to test whether or not fertiliser type and the density of planting have an effect on the yield of wheat. The dataset contains the following variables:

  • Final yield (kg per acre)—make sure to convert this to the most suitable SI unit before continuing with your analysis
  • Type of fertiliser (fertiliser type A, B, or C)
  • Planting density (1 = low density, 2 = high density)
  • Block in the field (north, east, south, west)

Fully analyse this dataset.

fert <- read.csv("../data/fertiliser_crop_data.csv")

# convert to SI units
fert <- fert |>
  mutate(mass = mass / 0.40468564224)

# are assumptions met? note that I also calculate the mean +/- SD here
fert %>%
  group_by(density) %>%
  summarise(mean = mean(mass),
            SD = sd(mass),
            mass_var = round(two_assum(mass)[1], 3),
            mass_norm = round(two_assum(mass)[2], 3))
# A tibble: 2 × 5
  density   mean    SD mass_var mass_norm
    <int>  <dbl> <dbl>    <dbl>     <dbl>
1       1 11889.  40.8    1668.     0.469
2       2 11920.  43.3    1877.     0.529
fert %>%
  group_by(block) %>%
  summarise(mean = mean(mass),
            SD = sd(mass),
            mass_var = round(two_assum(mass)[1], 3),
            mass_norm = round(two_assum(mass)[2], 3))
# A tibble: 4 × 5
  block   mean    SD mass_var mass_norm
  <chr>  <dbl> <dbl>    <dbl>     <dbl>
1 east  11925.  43.4    1882.     0.422
2 north 11894.  42.2    1781.     0.77 
3 south 11884.  39.7    1578.     0.212
4 west  11915.  43.7    1906.     0.21 
fert %>%
  group_by(fertilizer) %>%
  summarise(mean = mean(mass),
            SD = sd(mass),
            mass_var = round(two_assum(mass)[1], 3),
            mass_norm = round(two_assum(mass)[2], 3))
# A tibble: 3 × 5
  fertilizer   mean    SD mass_var mass_norm
  <chr>       <dbl> <dbl>    <dbl>     <dbl>
1 A          11887.  46.1    2122.     0.774
2 B          11899.  38.6    1490.     0.887
3 C          11927.  40.3    1623.     0.254
# yes, all assumptions check out, proceed with normal paramatric stats

# do an ANOVA and look at main effects first
aov1 <- aov(mass ~ density + block + fertilizer, data = fert)
summary(aov1)
            Df Sum Sq Mean Sq F value   Pr(>F)    
density      1  23164   23164  15.224 0.000184 ***
block        2   2199    1099   0.723 0.488329    
fertilizer   2  27444   13722   9.018 0.000269 ***
Residuals   90 136940    1522                     
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
# the block effect is not significant but density and fertilizer are

# let's check if the fertilizer type interacts with density
aov2 <- aov(mass ~ density * fertilizer, data = fert)
summary(aov2)
                   Df Sum Sq Mean Sq F value   Pr(>F)    
density             1  23164   23164  15.195 0.000186 ***
fertilizer          2  27444   13722   9.001 0.000273 ***
density:fertilizer  2   1935     967   0.635 0.532500    
Residuals          90 137203    1524                     
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
# no interaction effect is present, so the fertilizer has the same
# effect regardless of at which planting density it is applied

# lets see which planting fertilizer results in the greatest mass

TukeyHSD(aov2, which = "fertilizer", ordered = TRUE)
  Tukey multiple comparisons of means
    95% family-wise confidence level
    factor levels have been ordered

Fit: aov(formula = mass ~ density * fertilizer, data = fert)

$fertilizer
        diff        lwr      upr     p adj
B-A 11.84752 -11.414312 35.10935 0.4482026
C-A 40.29177  17.029945 63.55360 0.0002393
C-B 28.44426   5.182428 51.70609 0.0123951
TukeyHSD(aov2, which = "fertilizer", ordered = TRUE)
  Tukey multiple comparisons of means
    95% family-wise confidence level
    factor levels have been ordered

Fit: aov(formula = mass ~ density * fertilizer, data = fert)

$fertilizer
        diff        lwr      upr     p adj
B-A 11.84752 -11.414312 35.10935 0.4482026
C-A 40.29177  17.029945 63.55360 0.0002393
C-B 28.44426   5.182428 51.70609 0.0123951
plot(TukeyHSD(aov2, which = "fertilizer", ordered = TRUE))

# here we can see that the mass of crop produced by fertilizer C is the
# greatest, significantly more so compared to both A and B; the effect
# of fertilizer B is no different than that of A
#
# the second planting density also yields a greater mass per ha
#
# make sure the results are written up as appropriate for a journal,
# so indicate the d.f., S.S., and p-value

Question 8

Reflect on the project you intend doing during your Honours year. Specifically, focus on your experimental or sampling design (even though this might not be fully known at this stage), the nature of the data you anticipate obtaining, and the statistical analyses you will perform. Structure your response as follows:

  • Provide a brief Aim and state the Objectives
  • What are your predictions?
  • Write down the hypotheses you will test
  • Describe the experimental or sampling design that will support testing the hypotheses
  • Describe the data you anticipate obtaining
  • What statistical analyses will you perform on the data?

For those of you who will not generate data suitable for statistical analysis, please reflect on

The end

Submit the .html file wherein you provide answers to Questions 1–7 by no later than 19:00 today. Label the script as follows:

BCB744_<Name>_<Surname>_Summative_Task_2.html, e.g.

BCB744_AJ_Smit_Summative_Task_2.html.

Upload your .html files onto Google Forms.

Reuse

Citation

BibTeX citation:
@online{smit,_a._j.,
  author = {Smit, A. J.,},
  title = {BCB744 {(BioStatistics):} {Summative} {Task} 2, 12 {April}
    2024},
  date = {},
  url = {http://tangledbank.netlify.app/assessments/BCB744_Summative_2_2024.html},
  langid = {en}
}
For attribution, please cite this work as:
Smit, A. J. BCB744 (BioStatistics): Summative Task 2, 12 April 2024. http://tangledbank.netlify.app/assessments/BCB744_Summative_2_2024.html.