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.codeinto a binary variable. Thedplyr::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
tidyversepackage loads multiple useful libraries, includingdplyrandggplot2, 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
trtvariable having five instances of "trt1" and five of "trt2", and avaluevariable 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
Death Number of Subjects Mean Age (years) 0 17 33.35 1 3 36.33
1.2.2 Computation lab: Frequency distributions
R facilitates the computation and visualization of frequency distributions.
-
Discrete Data:
dplyr::group_by()anddplyr::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()andjanitor::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, withbinwidthcontrolling 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×IQR of the hinges (quartiles). - Numerical summaries like mean, median, standard deviation (SD), and inter-quartile range (IQR) can be computed using
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, anddplyr::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 k subjects to one treatment and n−k to another from a group of n subjects is given by the binomial coefficient (kn).
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., X).
- Observed Data: Specific values realized from a random variable. Denoted by lowercase letters (e.g., x).
- Probability Mass Function (PMF): p(xi)=P(X=xi) for discrete random variables.
- Probability Density Function (PDF): f(x) for continuous random variables, where f(x)≥0 and ∫−∞∞f(x)dx=1.
- Cumulative Distribution Function (CDF): F(x)=P(X≤x). For continuous variables, F′(x)=f(x). The CDF can be used to calculate probabilities for intervals: P(a<X<b)=F(b)−F(a).
- Quantile: The p-th quantile, xp, is the value such that F(xp)=p.
1.4.1 The binomial distribution
Models the number of successes (k) in a fixed number (n) of independent Bernoulli trials, where each trial has a probability of success (p). Denoted as X∼Bin(n,p).
- PMF: P(X=k)=(kn)pk(1−p)n−k.
- R Functions:
dbinom()for PMF,pbinom()for CDF. - Bernoulli Distribution: A special case where n=1.
1.4.2 The normal distribution
A ubiquitous continuous distribution characterized by its bell shape. It is defined by its mean (μ) and standard deviation (σ). Denoted as X∼N(μ,σ2).
- PDF: ϕ(x;μ,σ)=σ2π1exp(−21(σx−μ)2).
- Standard Normal Distribution: Z∼N(0,1), with PDF ϕ(x).
- Transformation: If Y∼N(μ,σ2), then Z=σY−μ∼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). Consequently, z1−p=−zp.
1.4.3 Chi-square distribution
Arises from the sum of squared standard normal random variables. If X1,…,Xn are i.i.d. N(0,1), then Y=∑i=1nXi2∼χn2, where n is the degrees of freedom (df).
- Properties: E(Y)=n, Var(Y)=2n.
- Shape: Right-skewed, becoming more normal-like as df increases.
- R Function:
pchisq()for CDF.
Application: The sample variance S2=n−1∑i=1n(Xi−Xˉ)2 from Xi∼N(0,1) follows σ2(n−1)S2∼χn−12.
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) and W∼χn2 are independent, then W/nX∼tn.
- 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,…,Xn are i.i.d. from N(μ,σ2), then Sn(Xˉ−μ)∼tn−1, where S 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∼χm2 and Y∼χn2 are independent, then W=Y/nX/m∼Fm,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) for X∼Bin(size,prob). - Normal:
pnorm(q, mean, sd)calculates P(X≤q) for X∼N(mean,sd2).qnorm(p, mean, sd)finds the p-th quantile. - Chi-Square:
pchisq(q, df)calculates P(X≤q) for X∼χdf2. - t Distribution:
pt(q, df)calculates P(X≤q) for X∼tdf. - F Distribution:
pf(q, df1, df2)calculates P(X≤q) for X∼Fdf1, 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
distributionanddparamsarguments 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 (H0), which represents a statement of no effect or no difference, and an alternative hypothesis (H1), which is the claim to be tested. The process aims to determine if the sample data provide sufficient evidence to reject H0 in favor of H1.
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, α), it suggests that the observed data are unlikely to have occurred if H0 were true, leading to its rejection.
Example: In comparing C-section rates between two hospitals, the null hypothesis (H0) is that the rates are equal (pMG=pNYG). 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 H0. 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^(1−p^)(1/n1+1/n2)p^MG−p^NYG
where p^MG and p^NYG are the observed proportions, p^ is the pooled proportion, and n1,n2 are the sample sizes. The p-value for a two-sided test is P(∣Z∣>∣z∣).
The following table summarizes the key aspects of hypothesis testing:
| Approach | Methodology | p-value Interpretation |
|---|---|---|
| Simulation-based | Simulates data under H0 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 H0. |
| Model-based | Uses 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 H0. 12 |
2.1.3 Errors in hypothesis testing
Two types of errors can occur in hypothesis testing:
- Type I Error: Rejecting the null hypothesis (H0) when it is actually true. The probability of a Type I error is denoted by α and is often set as the significance level of the test.
- Type II Error: Failing to reject the null hypothesis (H0) when the alternative hypothesis (H1) is true. The probability of a Type II error is denoted by β.
The power of a test is defined as 1−β, which is the probability of correctly rejecting H0 when H1 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 For a mean (μ) from a normal distribution with known variance, a (1−α)×100% confidence interval is: Xˉ±z1−α/2nσ where Xˉ is the sample mean, σ is the population standard deviation, n is the sample size, and z1−α/2 is the (1−α/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ˉ from an i.i.d. sequence of random variables with mean μ and variance σ2, the Central Limit Theorem states that for large n, Xˉ is approximately normally distributed: Xˉ∼N(μ,nσ2) This approximation allows for the construction of confidence intervals for μ. A (1−α)×100% confidence interval for μ is typically given by: Xˉ−z1−α/2nσ<μ<Xˉ+z1−α/2nσ or, if σ is unknown and estimated by the sample standard deviation s: Xˉ−tn−1,1−α/2ns<μ<Xˉ+tn−1,1−α/2ns where tn−1,1−α/2 is the (1−α/2) quantile of the t-distribution with n−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 (y) and a single quantitative independent variable (x) using the equation: yi=β0+β1xi+ϵi where β0 is the intercept, β1 is the slope, and ϵi is the error term, assumed to have a mean of 0 and constant variance.
Least-squares regression is commonly used to estimate β0 and β1 by minimizing the sum of squared residuals (∑ϵi2). The estimated coefficients are: β^1=rSxSy β^0=yˉ−β^1xˉ where r is the correlation between x and y, and Sx,Sy are the sample standard deviations of x and y, respectively.
The coefficient of determination (R2) is a measure of model fit, representing the proportion of the total variation in the dependent variable (y) that is explained by the independent variable (x) in a simple linear regression: R2=1−∑i=1n(yi−yˉ)2∑i=1nei2 where ei 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,…,xk), the model extends to multiple linear regression: yi=β0+β1xi1+β2xi2+⋯+βkxik+ϵi In matrix notation, this can be represented as: y=Xβ+ϵ The least squares estimator for the coefficient vector β is: β^=(XTX)−1XTy The covariance matrix of β^ is: cov(β^)=(XTX)−1σ2 where σ2 is the variance of the error terms. An estimator for σ2 is σ^2=n−k−11∑i=1n(yi−y^i)2, where 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 k categories, k−1 indicator variables are typically used when the model includes an intercept, or k 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 usingggplot_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) for a continuous random variable X, where F is the cumulative distribution function. Investigate whether this equality holds for a discrete random variable.
-
Exercise 2.6: Utilize R functions
dnormandpnormto compute normal density and cumulative distribution functions.- For given values of μ, σ, and y, determine what
dnorm(y, mu, sigma)computes. Express this value in terms of the standard normal density ϕ and standard normal cumulative distribution function Φ. Compare this value to 1/σ⋅ϕ((y−μ)/σ) and explain any differences. - Similarly, for given values of μ, σ, and y, determine what
pnorm(y, mu, sigma)computes. Express this value in terms of Φ((y−μ)/σ) and explain any differences.
- For given values of μ, σ, and y, determine what
-
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_qqandgeom_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_elsewithinmutateis 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.
- Confirm the total number of possible random treatment assignments for 10 patients out of 20 using the R command
3.1.3 Exercises focusing on statistical distributions and matrix algebra
-
Exercise 2.7: Assume X and Y are independent for any positive integer n, and let Wn∼χn2. Let Vn=X/Wn/n.
- Given X∼N(0,1), show that Vn follows an F distribution and specify its parameters.
- Simulate 1,000 samples of X, Wn, and Vn using the
rtfunction in R and plot histograms for each variable. - Identify the theoretical density functions for X, Wn, and Vn. 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 σ.
- 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, β.
- 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 β 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_childmortdata 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.