designexptr org

1. Introduction to statistical data handling in R

This section provides a foundational overview of data handling in R, covering data input, manipulation, summarization, generation, and the visualization of distributions, along with an introduction to theoretical probability distributions.

1.1 Data handling in R

R is a powerful tool for statistical analysis, and its capabilities extend to efficient data handling. This involves reading data into R, manipulating it into a usable format, summarizing key characteristics, and generating new data when necessary. The tidyverse collection of packages, along with base R functions, are instrumental in these processes.

1.1.1 Reading data into R

Data, typically stored in computer files, must be imported into R for analysis. The data.frame is the most common structure for storing data in R. Text files in comma-separated value (CSV) format can be imported using functions like read.csv(). For specific datasets included in packages, helper functions may be available.

1.1.2 Manipulating data in R

Raw data often requires cleaning and restructuring, a process known as data wrangling. Base R and the dplyr library within tidyverse offer numerous functions for this purpose. This includes recoding variables, converting data types, and managing categorical data using factors.

Example: Recoding an ordinal categorical variable like education.code into a binary variable. The dplyr::recode() function can map specific integer codes to new categories (e.g., mapping codes 4 and 5 to 1, and codes 1, 2, and 3 to 0).

1.1.3 Summarizing data using R

Quantitative and visual summaries are crucial for understanding data. Quantitative summaries are often presented in tables, while visual summaries utilize graphs. The tidyverse library, particularly dplyr and ggplot2, provides tools for these tasks. The pipe operator (%>%) facilitates chaining multiple operations efficiently.

  • dplyr::count(): Computes the frequency of distinct values in a column.
  • dplyr::mutate(): Creates new columns or modifies existing ones, often used to calculate percentages.
  • dplyr::summarise(): Computes summary statistics such as count (n()), mean (mean()), median (median()), and standard deviation (sd()) for columns.
  • ggplot2: Used for creating high-quality static and interactive graphics, including bar charts and histograms.

Note: The tidyverse package loads multiple useful libraries, including dplyr and ggplot2, simplifying their use.

1.1.4 Generating data in R

Generating data is a common practice in study design, allowing for the simulation of scenarios, replication of values, combination of variables, or sampling from known probability distributions.

  • sample(): Used to draw random samples from a specified set of values.
  • set.seed(): Ensures reproducibility of random number generation by initializing the random number generator.
  • expand.grid(): Creates a data frame from all possible combinations of specified vectors.
  • arrange(): Sorts the data frame based on one or more columns.

Example: Creating a data frame with a trt variable having five instances of "trt1" and five of "trt2", and a value variable with ten random integers between 1 and 1,000,000.

1.2 Frequency distributions

A frequency distribution describes how often each distinct value (for discrete data) or values within specific intervals (for continuous data) occur in a dataset.

1.2.1 Discrete and continuous data

  • Discrete Data: Characterized by a finite or countably infinite number of distinct values. Outcomes like survival (1 for dead, 0 for alive) are discrete.
  • Continuous Data: Can take on any value within a given range, forming a continuum. Age is an example of continuous data.

Table: Frequency Distribution of Survival

DeathNumber of SubjectsMean Age (years)
01733.35
1336.33

1.2.2 Computation lab: Frequency distributions

R facilitates the computation and visualization of frequency distributions.

  • Discrete Data:

    • dplyr::group_by() and dplyr::summarise() can be used to count occurrences and calculate summary statistics (like mean age) for different categories.
    • ggplot2::geom_bar() creates bar charts to visualize the frequency of discrete outcomes.
    • janitor::tabyl() and janitor::adorn_*() functions are useful for generating cross-tabulations and relative frequency distributions.

    Example: Displaying the frequency and relative frequency distribution of survival in a COVID-19 treatment study, broken down by treatment group (TRT vs. PLA).

  • Continuous Data:

    • Numerical summaries like mean, median, standard deviation (SD), and inter-quartile range (IQR) can be computed using dplyr::summarise().
    • ggplot2::geom_histogram() is used to visualize the distribution of continuous data, with binwidth controlling the interval size. Histograms can display counts or densities.
    • ggplot2::geom_boxplot() provides a visual summary of the distribution, showing quartiles, median, and potential outliers.

    Important: A histogram with aes(y = ..density..) plots density on the vertical axis, where the area of the rectangles sums to one. The boxplot's whiskers extend to values within 1.5×IQR1.5 \times IQR of the hinges (quartiles).

1.3 Randomization

Randomization plays a critical role in both sampling from a population and assigning treatments in experimental studies.

1.3.1 Computation lab: Randomization

R provides functions to implement various randomization schemes.

  • Simple Random Sampling: sample() can select a specified number of unique elements from a population with equal probability. This is used to draw a representative sample.
  • Treatment Assignment: For experiments, randomization ensures that treatment groups are balanced. Functions like dplyr::sample_n() can randomly select subjects for a treatment group, and dplyr::anti_join() can identify those not selected for the control group. dplyr::bind_rows() can then combine these groups.

Concept: The number of ways to assign kk subjects to one treatment and n−kn-k to another from a group of nn subjects is given by the binomial coefficient (nk)\binom{n}{k}.

1.4 Theoretical distributions

Theoretical probability distributions describe the idealized behavior of random variables. These distributions are characterized by specific probability mass functions (for discrete variables) or probability density functions (for continuous variables).

  • Random Variable: A function that maps outcomes from a sample space to real numbers. Denoted by uppercase letters (e.g., XX).
  • Observed Data: Specific values realized from a random variable. Denoted by lowercase letters (e.g., xx).
  • Probability Mass Function (PMF): p(xi)=P(X=xi)p(x_i) = P(X = x_i) for discrete random variables.
  • Probability Density Function (PDF): f(x)f(x) for continuous random variables, where f(x)≥0f(x) \ge 0 and ∫−∞∞f(x)dx=1\int_{-\infty}^{\infty} f(x) dx = 1.
  • Cumulative Distribution Function (CDF): F(x)=P(X≤x)F(x) = P(X \le x). For continuous variables, F′(x)=f(x)F'(x) = f(x). The CDF can be used to calculate probabilities for intervals: P(a<X<b)=F(b)−F(a)P(a < X < b) = F(b) - F(a).
  • Quantile: The pp-th quantile, xpx_p, is the value such that F(xp)=pF(x_p) = p.

1.4.1 The binomial distribution

Models the number of successes (kk) in a fixed number (nn) of independent Bernoulli trials, where each trial has a probability of success (pp). Denoted as X∼Bin(n,p)X \sim \text{Bin}(n, p).

  • PMF: P(X=k)=(nk)pk(1−p)n−kP(X=k) = \binom{n}{k} p^k (1-p)^{n-k}.
  • R Functions: dbinom() for PMF, pbinom() for CDF.
  • Bernoulli Distribution: A special case where n=1n=1.

1.4.2 The normal distribution

A ubiquitous continuous distribution characterized by its bell shape. It is defined by its mean (μ\mu) and standard deviation (σ\sigma). Denoted as X∼N(μ,σ2)X \sim N(\mu, \sigma^2).

  • PDF: ϕ(x;μ,σ)=1σ2πexp⁡(−12(x−μσ)2)\phi(x; \mu, \sigma) = \frac{1}{\sigma\sqrt{2\pi}} \exp\left(-\frac{1}{2}\left(\frac{x-\mu}{\sigma}\right)^2\right).
  • Standard Normal Distribution: Z∼N(0,1)Z \sim N(0, 1), with PDF ϕ(x)\phi(x).
  • Transformation: If Y∼N(μ,σ2)Y \sim N(\mu, \sigma^2), then Z=Y−μσ∼N(0,1)Z = \frac{Y-\mu}{\sigma} \sim N(0, 1).
  • R Functions: dnorm() for PDF, pnorm() for CDF, qnorm() for quantiles.
  • Symmetry: The normal density is symmetric around its mean: ϕ(μ−x)=ϕ(μ+x)\phi(\mu - x) = \phi(\mu + x). Consequently, z1−p=−zpz_{1-p} = -z_p.

1.4.3 Chi-square distribution

Arises from the sum of squared standard normal random variables. If X1,…,XnX_1, \dots, X_n are i.i.d. N(0,1)N(0,1), then Y=∑i=1nXi2∼χn2Y = \sum_{i=1}^n X_i^2 \sim \chi^2_n, where nn is the degrees of freedom (df).

  • Properties: E(Y)=nE(Y) = n, Var(Y)=2nVar(Y) = 2n.
  • Shape: Right-skewed, becoming more normal-like as df increases.
  • R Function: pchisq() for CDF.

Application: The sample variance S2=∑i=1n(Xi−Xˉ)2n−1S^2 = \frac{\sum_{i=1}^n (X_i - \bar{X})^2}{n-1} from Xi∼N(0,1)X_i \sim N(0,1) follows (n−1)S2σ2∼χn−12\frac{(n-1)S^2}{\sigma^2} \sim \chi^2_{n-1}.

1.4.4 t distribution

Arises from the ratio of a standard normal variable to the square root of a chi-square variable divided by its degrees of freedom. If X∼N(0,1)X \sim N(0,1) and W∼χn2W \sim \chi^2_n are independent, then XW/n∼tn\frac{X}{\sqrt{W/n}} \sim t_n.

  • Properties: Symmetric about 0, with heavier tails than the normal distribution for small degrees of freedom. As df increases, it approaches the normal distribution.
  • R Function: pt() for CDF.

Application: If X1,…,XnX_1, \dots, X_n are i.i.d. from N(μ,σ2)N(\mu, \sigma^2), then n(Xˉ−μ)S∼tn−1\frac{\sqrt{n}(\bar{X} - \mu)}{S} \sim t_{n-1}, where SS is the sample standard deviation.

1.4.5 F distribution

Arises from the ratio of two independent chi-square variables, each divided by their respective degrees of freedom. If X∼χm2X \sim \chi^2_m and Y∼χn2Y \sim \chi^2_n are independent, then W=X/mY/n∼Fm,nW = \frac{X/m}{Y/n} \sim F_{m,n}.

  • Properties: Right-skewed.
  • R Function: pf() for CDF.

Application: The ratio of sample variances from two normally distributed populations can follow an F-distribution.

1.4.6 Computation lab: Theoretical distributions

R provides functions to compute probabilities, quantiles, and densities for these theoretical distributions.

  • Binomial: pbinom(q, size, prob) calculates P(X≤q)P(X \le q) for X∼Bin(size,prob)X \sim \text{Bin}(\text{size}, \text{prob}).
  • Normal: pnorm(q, mean, sd) calculates P(X≤q)P(X \le q) for X∼N(mean,sd2)X \sim N(\text{mean}, \text{sd}^2). qnorm(p, mean, sd) finds the pp-th quantile.
  • Chi-Square: pchisq(q, df) calculates P(X≤q)P(X \le q) for X∼χdf2X \sim \chi^2_{\text{df}}.
  • t Distribution: pt(q, df) calculates P(X≤q)P(X \le q) for X∼tdfX \sim t_{\text{df}}.
  • F Distribution: pf(q, df1, df2) calculates P(X≤q)P(X \le q) for X∼Fdf1, df2X \sim F_{\text{df1, df2}}.

Tip: Use help("distributions") in R to get a list of available distribution functions.

1.5 Quantile-Quantile Plots

Quantile-quantile (Q-Q) plots are graphical tools for comparing two probability distributions by plotting their quantiles against each other. They are particularly useful for assessing whether a sample of data follows a specific theoretical distribution.

1.5.1 Quantile-quantile plot interpretation

  • Procedure: Ordered sample values (order statistics) are plotted against their expected theoretical quantiles. If the sample distribution matches the theoretical distribution, the points on the Q-Q plot should lie approximately along a straight line.
  • Reference Line: A line connecting the first and third quartiles of the theoretical distribution can serve as a visual guide.
  • Deviations: Systematic deviations from the line indicate that the sample data does not conform to the hypothesized distribution.

Example: A Q-Q plot comparing a sample to a standard normal distribution. If the points follow the reference line, the sample is likely normally distributed. Deviations at the tails might indicate heavier or lighter tails than the normal distribution.

  • R Implementation (ggplot2):
    • geom_qq(): Generates the Q-Q plot.
    • geom_qq_line(): Adds a reference line.
    • The distribution and dparams arguments can be used to specify theoretical distributions other than the default standard normal.

Important: When assessing normality, comparing the mean and median, the standard deviation and IQR, and examining histograms alongside Q-Q plots provides a more comprehensive evaluation.

2. Statistical inference: hypothesis testing and confidence intervals

Statistical inference provides frameworks for drawing conclusions about population parameters based on sample data, primarily through hypothesis testing and confidence intervals.

2.1 Introduction to hypothesis testing

Hypothesis testing is a formal procedure used to assess evidence for a claim about a population parameter using sample data. It involves formulating a null hypothesis (H0H_0), which represents a statement of no effect or no difference, and an alternative hypothesis (H1H_1), which is the claim to be tested. The process aims to determine if the sample data provide sufficient evidence to reject H0H_0 in favor of H1H_1.

2.1.1 Simulation-based hypothesis testing

This approach involves simulating data under the assumption that the null hypothesis is true. By repeatedly generating data and calculating a test statistic from these simulated datasets, we can construct an empirical sampling distribution of the test statistic. The p-value is then calculated as the proportion of simulated test statistics that are as extreme or more extreme than the observed test statistic from the actual data. If this p-value is small (typically below a pre-determined significance level, α\alpha), it suggests that the observed data are unlikely to have occurred if H0H_0 were true, leading to its rejection.

Example: In comparing C-section rates between two hospitals, the null hypothesis (H0H_0) is that the rates are equal (pMG=pNYGp_{MG} = p_{NYG}). Data are shuffled to simulate scenarios where hospital labels are randomly assigned to births, assuming equal C-section probabilities. The distribution of the difference in proportions from these simulations forms the sampling distribution under H0H_0. The observed difference is then compared to this distribution to calculate a p-value.

2.1.2 Model-based hypothesis testing

Model-based hypothesis testing relies on theoretical distributions, often derived from mathematical models like the binomial or normal distribution, to approximate the sampling distribution of a test statistic. This method typically involves calculating a test statistic and its associated p-value using statistical formulas.

Example: For comparing proportions, the theoretical sampling distribution of the difference in proportions can be approximated by a normal distribution under the null hypothesis. A z-statistic is calculated, and the p-value is determined using the standard normal cumulative distribution function.

z=p^MG−p^NYGp^(1−p^)(1/n1+1/n2)z = \frac{\hat{p}_{MG} - \hat{p}_{NYG}}{\sqrt{\hat{p}(1-\hat{p})(1/n_1 + 1/n_2)}}

where p^MG\hat{p}_{MG} and p^NYG\hat{p}_{NYG} are the observed proportions, p^\hat{p} is the pooled proportion, and n1,n2n_1, n_2 are the sample sizes. The p-value for a two-sided test is P(∣Z∣>∣z∣)P(|Z| > |z|).

The following table summarizes the key aspects of hypothesis testing:

ApproachMethodologyp-value Interpretation
Simulation-basedSimulates data under H0H_0 to empirically derive the sampling distribution of the test statistic.The proportion of simulated test statistics as extreme or more extreme than the observed statistic. A small p-value suggests strong evidence against H0H_0.
Model-basedUses theoretical probability distributions (e.g., normal, t) to approximate the sampling distribution.Derived from the theoretical distribution of the test statistic (e.g., z-test, t-test). A small p-value indicates that the observed data are unlikely under H0H_0. 12

2.1.3 Errors in hypothesis testing

Two types of errors can occur in hypothesis testing:

  • Type I Error: Rejecting the null hypothesis (H0H_0) when it is actually true. The probability of a Type I error is denoted by α\alpha and is often set as the significance level of the test.
  • Type II Error: Failing to reject the null hypothesis (H0H_0) when the alternative hypothesis (H1H_1) is true. The probability of a Type II error is denoted by β\beta.

The power of a test is defined as 1−β1 - \beta, which is the probability of correctly rejecting H0H_0 when H1H_1 is true.

2.2 Confidence intervals

A confidence interval (CI) provides a range of plausible values for an unknown population parameter based on sample data. It quantifies the uncertainty associated with estimating a parameter from a sample.

2.2.1 Construction and interpretation

A confidence interval is typically constructed as: Point Estimate±Margin of Error\text{Point Estimate} \pm \text{Margin of Error} For a mean (μ\mu) from a normal distribution with known variance, a (1−α)×100%(1-\alpha) \times 100\% confidence interval is: Xˉ±z1−α/2σn\bar{X} \pm z_{1-\alpha/2} \frac{\sigma}{\sqrt{n}} where Xˉ\bar{X} is the sample mean, σ\sigma is the population standard deviation, nn is the sample size, and z1−α/2z_{1-\alpha/2} is the (1−α/2)(1-\alpha/2) quantile of the standard normal distribution.

The interpretation of a confidence interval is crucial: a 95% confidence interval means that if the same sampling procedure were repeated many times, 95% of the constructed intervals would contain the true population parameter. It is incorrect to state that there is a 95% probability that the true parameter lies within a specific calculated interval.

Example: A simulation demonstrates that out of 1000 calculated 95% confidence intervals for a population mean, 947 contained the true mean. This aligns with the theoretical expectation that approximately 95% of such intervals should capture the true parameter in the long run 14.

Reminder: The uncertainty in a confidence interval arises from the variability in the sampling process, not from uncertainty about the true parameter itself.

2.2.2 Confidence intervals for means

For a sample mean Xˉ\bar{X} from an i.i.d. sequence of random variables with mean μ\mu and variance σ2\sigma^2, the Central Limit Theorem states that for large nn, Xˉ\bar{X} is approximately normally distributed: Xˉ∼N(μ,σ2n)\bar{X} \sim N\left(\mu, \frac{\sigma^2}{n}\right) This approximation allows for the construction of confidence intervals for μ\mu. A (1−α)×100%(1-\alpha) \times 100\% confidence interval for μ\mu is typically given by: Xˉ−z1−α/2σn<μ<Xˉ+z1−α/2σn\bar{X} - z_{1-\alpha/2}\frac{\sigma}{\sqrt{n}} < \mu < \bar{X} + z_{1-\alpha/2}\frac{\sigma}{\sqrt{n}} or, if σ\sigma is unknown and estimated by the sample standard deviation ss: Xˉ−tn−1,1−α/2sn<μ<Xˉ+tn−1,1−α/2sn\bar{X} - t_{n-1, 1-\alpha/2}\frac{s}{\sqrt{n}} < \mu < \bar{X} + t_{n-1, 1-\alpha/2}\frac{s}{\sqrt{n}} where tn−1,1−α/2t_{n-1, 1-\alpha/2} is the (1−α/2)(1-\alpha/2) quantile of the t-distribution with n−1n-1 degrees of freedom.

2.3 Linear regression

Linear regression models the relationship between a dependent variable and one or more independent variables by fitting a linear equation.

2.3.1 Simple linear regression

Simple linear regression models the relationship between a quantitative dependent variable (yy) and a single quantitative independent variable (xx) using the equation: yi=β0+β1xi+ϵiy_i = \beta_0 + \beta_1 x_i + \epsilon_i where β0\beta_0 is the intercept, β1\beta_1 is the slope, and ϵi\epsilon_i is the error term, assumed to have a mean of 0 and constant variance.

Least-squares regression is commonly used to estimate β0\beta_0 and β1\beta_1 by minimizing the sum of squared residuals (∑ϵi2\sum \epsilon_i^2). The estimated coefficients are: β^1=rSySx\hat{\beta}_1 = r \frac{S_y}{S_x} β^0=yˉ−β^1xˉ\hat{\beta}_0 = \bar{y} - \hat{\beta}_1 \bar{x} where rr is the correlation between xx and yy, and Sx,SyS_x, S_y are the sample standard deviations of xx and yy, respectively.

The coefficient of determination (R2R^2) is a measure of model fit, representing the proportion of the total variation in the dependent variable (yy) that is explained by the independent variable (xx) in a simple linear regression: R2=1−∑i=1nei2∑i=1n(yi−yˉ)2R^2 = 1 - \frac{\sum_{i=1}^n e_i^2}{\sum_{i=1}^n (y_i - \bar{y})^2} where eie_i are the residuals.

Example: The relationship between life satisfaction and childhood mortality can be modeled using simple linear regression, where life satisfaction is the dependent variable and the logarithm of childhood mortality is the independent variable. The estimated coefficients indicate the change in life satisfaction for a unit change in the log of childhood mortality (#page=15=16) 15 16.

2.3.2 Multiple linear regression

When there are multiple independent variables (x1,x2,…,xkx_1, x_2, \ldots, x_k), the model extends to multiple linear regression: yi=β0+β1xi1+β2xi2+⋯+βkxik+ϵiy_i = \beta_0 + \beta_1 x_{i1} + \beta_2 x_{i2} + \cdots + \beta_k x_{ik} + \epsilon_i In matrix notation, this can be represented as: y=Xβ+ϵ\mathbf{y} = \mathbf{X}\boldsymbol{\beta} + \boldsymbol{\epsilon} The least squares estimator for the coefficient vector β\boldsymbol{\beta} is: β^=(XTX)−1XTy\hat{\boldsymbol{\beta}} = (\mathbf{X}^T\mathbf{X})^{-1}\mathbf{X}^T\mathbf{y} The covariance matrix of β^\hat{\boldsymbol{\beta}} is: cov(β^)=(XTX)−1σ2\text{cov}(\hat{\boldsymbol{\beta}}) = (\mathbf{X}^T\mathbf{X})^{-1}\sigma^2 where σ2\sigma^2 is the variance of the error terms. An estimator for σ2\sigma^2 is σ^2=1n−k−1∑i=1n(yi−y^i)2\hat{\sigma}^2 = \frac{1}{n-k-1}\sum_{i=1}^n (y_i - \hat{y}_i)^2, where y^i\hat{y}_i are the predicted values.

2.3.3 Categorical covariates in regression

Categorical independent variables can be incorporated into regression models using indicator (dummy) variables. If a categorical variable has kk categories, k−1k-1 indicator variables are typically used when the model includes an intercept, or kk indicator variables if the model does not include an intercept but has slopes for the categorical variable. Each indicator variable takes a value of 1 if the observation belongs to a specific category and 0 otherwise. The coefficient of an indicator variable represents the difference in the dependent variable between that category and the reference category (the one excluded from the model).

Example: Modeling life satisfaction by region involves using indicator variables for each region, with one region designated as the reference category. The coefficients for the other regions quantify the average difference in life satisfaction compared to the reference region 17.

2.3.4 Regression diagnostics

Diagnostic checks are essential to assess the validity of the assumptions underlying linear regression models. Key diagnostics include:

  • Residual plots: Examining plots of residuals against fitted values to check for non-constant variance (heteroscedasticity) or non-linear patterns.
  • Normal Q-Q plots: Assessing the normality of residuals by comparing their quantiles to theoretical quantiles of a normal distribution.

Violations of these assumptions (e.g., heteroscedasticity or non-normality of residuals) do not inherently bias the least-squares estimates but can affect the reliability of standard errors and hypothesis tests for the regression coefficients.

3. Exercises and concluding remarks

This section provides a series of exercises designed to solidify understanding of the chapter's concepts, followed by concluding remarks about the book.

3.1 Exercises

The following exercises are designed to reinforce the statistical and computational concepts presented in the chapter, utilizing the R programming language for practical application.

3.1.1 Exercises focusing on graphical representation and probability distributions

  • Exercise 2.2: Reproduce Figure 2.4 using geom_histogram(aes(y = ..density..)) to create a density histogram. This exercise involves using ggplot_build() to extract the computed histogram values and verify that the sum of the areas of all bars in the density histogram equals 1.

  • Exercise 2.5: Demonstrate the property that P(a<X<b)=F(b)−F(a)P(a < X < b) = F(b) - F(a) for a continuous random variable XX, where FF is the cumulative distribution function. Investigate whether this equality holds for a discrete random variable.

  • Exercise 2.6: Utilize R functions dnorm and pnorm to compute normal density and cumulative distribution functions.

    • For given values of μ\mu, σ\sigma, and yy, determine what dnorm(y, mu, sigma) computes. Express this value in terms of the standard normal density ϕ\phi and standard normal cumulative distribution function Φ\Phi. Compare this value to 1/σ⋅ϕ((y−μ)/σ)1/\sigma \cdot \phi((y - \mu)/\sigma) and explain any differences.
    • Similarly, for given values of μ\mu, σ\sigma, and yy, determine what pnorm(y, mu, sigma) computes. Express this value in terms of Φ((y−μ)/σ)\Phi((y - \mu)/\sigma) and explain any differences.
  • Exercise 2.8: Explain the rationale behind using the first and third quartiles from an ordered sample for the reference line in Figure 2.12.

  • Exercise 2.9: Build upon Exercise 2.7 by plotting Q-Q plots for simulated squared values against appropriate F distributions using geom_qq and geom_qq_line. Comment on the visual representation of the distribution.

  • Exercise 2.10: Replicate the data generation process for Figure 2.16. This involves computing mean values for each column, pivoting the data into a long format, and then computing mean values per simulation using group_by. Verify that the reproduced plot is identical to the original Figure 2.16.

3.1.2 Exercises focusing on sampling and treatment assignment

  • Exercise 2.3: Consider a scenario with 20 patients randomly selected from a population of 25,000.

    • Explain the formula for calculating the probability of choosing a random sample of 20 patients from 25,000.
    • Use R to randomly select 4 patients from a total of 8, and calculate the probability of obtaining this specific random sample.
  • Exercise 2.4: This exercise explores random treatment assignments.

    • Confirm the total number of possible random treatment assignments for 10 patients out of 20 using the R command combn(covid_sampleUSDid, 10).
    • Implement and discuss the procedure of randomly selecting 10 patients for the active treatment first, then assigning the placebo to the remainder, and compare it to randomly selecting a column from the matrix of all possible assignments. The use of if_else within mutate is suggested for assigning treatments based on conditions.
    • Implement an alternative procedure in R where each patient is assigned to "TRT" or "PLA" with equal probabilities independently. Discuss whether this procedure yields desired random assignments.
    • Propose and implement a novel procedure in R for randomly assigning 10 patients to the active treatment, and verify that it results in random assignments.

3.1.3 Exercises focusing on statistical distributions and matrix algebra

  • Exercise 2.7: Assume XX and YY are independent for any positive integer nn, and let Wn∼χn2W_n \sim \chi^2_n. Let Vn=X/Wn/nV_n = X / \sqrt{W_n / n}.

    • Given X∼N(0,1)X \sim N(0,1), show that VnV_n follows an F distribution and specify its parameters.
    • Simulate 1,000 samples of XX, WnW_n, and VnV_n using the rt function in R and plot histograms for each variable.
    • Identify the theoretical density functions for XX, WnW_n, and VnV_n. Use R's df() function to plot these theoretical density curves alongside the histograms generated in the previous step. Comment on the visual alignment between the density curves and the histograms.
  • Exercise 2.11: This exercise involves a problem of weighing objects using a balance scale, with a standard deviation of weighing denoted by σ\sigma.

    • Yates' Procedure: Represent Yates' procedure, which involves weighing objects individually and in groups, in matrix form. Derive the least squares estimates for the unknown weights, β\beta.
    • Hotelling's Modification: Represent Hotelling's modification, where objects not included in a weighing are placed on the opposite pan, in matrix form. Derive the least squares estimate for β\beta in this scenario.
    • Calculate the variance of a weight estimate for both Yates' and Hotelling's procedures.
    • Recommend the more precise procedure for the chemist and justify the recommendation based on the calculated variances.
  • Exercise 2.12: Investigate whether life satisfaction changes by region over time using the lifesat_childmort data from Example 2.15.

3.2 Concluding remarks

This book, titled "Design and Analysis of Experiments and Observational Studies using R: A Volume in the Chapman & Hall/CRC Texts in Statistical Science Series," was authored by Nathan Taback. It was last updated on 2023-01-19 and was generated using the bookdown R package. This final section serves as a capstone, reinforcing the practical application of the statistical concepts through exercises and providing contextual information about the book itself.

Common mistakes to avoid

  • Review all topics thoroughly before exams
  • Pay attention to formulas and key definitions
  • Practice with examples provided in each section
  • Don't memorize without understanding the underlying concepts

© 2026 Maeve. All rights reserved. This content is protected by copyright.

See also