Using R Software for Statistical Analysis
The Analysis Workflow in R: Import, Inspect, Summarize, Visualize, Model, Interpret
The shape of an analysis in R
Nearly every analysis in R follows the same five movements, and recognising them makes unfamiliar code much easier to read:
- Import the data into a data frame.
- Inspect and transform it: check the dimensions, check each column's type, fix types that were guessed wrongly, create derived variables.
- Summarize it numerically, overall and by group.
- Visualize it, before fitting anything.
- Model it, then interpret the output in the units of the problem.
The order matters. Most analysis errors are not statistical mistakes but type mistakes and shape mistakes discovered too late, so the habit of inspecting immediately after importing pays for itself constantly.
Import
A rectangular text file is read with read.csv(), which returns a data frame:
survey <- read.csv("data/survey.csv")
A data frame is a list of equal-length columns, where each column is a vector with its own type but all columns share the same length.
That is the structure almost every modelling and plotting function in R expects. Note that from R 4.0 onward character columns are kept as character by default rather than being silently converted to factors.
Formula-based modelling functions such as lm() and aov() will usually coerce a character predictor to a factor when they build the model frame, so an explicit conversion is not always required simply to fit a model; converting deliberately with factor() is recommended whenever the set of allowed levels, their order, or the reference category matters.
Inspect and transform
Three functions answer three different questions, and choosing the right one is a small but real skill.
- dim(survey) returns the number of rows and columns, the fastest check that the file was parsed as expected rather than being read as one wide column.
- str(survey) prints the structure: the class of the object, its dimensions, and for each column its name, its type, and its first few values. This is the diagnostic tool, because it shows type mistakes directly, a numeric column read as character usually means a stray symbol or thousands separator in the file.
- summary(survey) prints per-column statistics: quartiles and the mean for numeric columns, counts for factors. This describes the data rather than diagnosing its representation.
head(survey) shows the first rows, which is useful for a quick look but reports nothing about types.
Columns are addressed with $, as in survey$score, and rows are selected by a logical condition, as in survey[survey$score > 70, ], note the comma, which says "all columns". Converting a categorical column is a single assignment:
survey$group <- factor(survey$group)
A factor stores its categories as levels. Under R's usual treatment contrasts for an unordered factor in a model with an intercept, the first level is the reference category.
Other contrast settings or parameterizations can represent factors differently. levels(survey$group) shows them, and table(survey$group) counts them, a quick way to catch a typo that has silently created an extra category.
Summarize
Overall summaries come from mean(), median(), sd(), var(), quantile(), and length(). Group summaries are the more common need, and R's formula interface expresses them compactly:
aggregate(score ~ group, data = survey, FUN = mean)
The formula score ~ group reads "score explained by group", and the same notation recurs throughout R, in boxplot(), in t.test(), in aov(), and in lm().
Learning it once pays off everywhere. tapply(survey$score, survey$group, mean, na.rm = TRUE) computes the same group means as the formula call after omitting missing scores, for groups with at least one observed score.
If a represented group has no observed scores, this call returns NaN while formula-based aggregate() omits that group. table() cross-tabulates two categorical variables.
Visualize
Plot before modelling, always. hist(survey$score) shows a distribution's shape and any impossible values; boxplot(score ~ group, data = survey) compares groups and exposes unequal spread; plot(survey$hours, survey$score) shows whether a relationship is plausibly linear before a line is fitted to it.
A scatterplot routinely reveals curvature, a ceiling effect, or a cluster of duplicated values that no summary statistic would have flagged.
Model, then interpret
Two workhorse calls cover most introductory work.
t.test(score ~ group, data = survey) compares the means of two independent groups, performing Welch's version by default, which does not assume equal variances.
A paired comparison is a different test, and it is written a different way. paired = TRUE belongs to the two-vector form, t.test(before, after, paired = TRUE); the formula method refuses it, and R 4.4.0 and later stop with cannot use 'paired' in formula method.
As a formula a paired test is t.test(Pair(before, after) ~ 1, data = survey), with the two matched measurements in two columns.
The syntax is the smaller half of the point: pairing is a property of the design, so a paired test is appropriate only when the two measurements come from the same unit, and applying it to independent groups answers a question nobody asked.
fit <- lm(score ~ hours, data = survey) fits a linear regression, and summary(fit) reports the coefficient table, the residual standard error, and R-squared.
Interpretation should always be returned to the units of the problem: a slope is the predicted change in the response for a one-unit increase in the predictor, and the intercept is the predicted response when the predictor is zero, a value that is frequently an extrapolation far outside the observed data and should not be over-read.
Finally, keep three claims separate. A p-value addresses whether an observed association is distinguishable from what the model's null hypothesis would produce.
R-squared addresses how much of the response's variability the fitted model accounts for. Neither addresses causation, which is settled by the design that produced the data, not by any function call.
R will fit a model to any numbers it is given, and interpreting the output responsibly is the analyst's job, not the software's.
Mark Yourself Question
- Grab a piece of paper and try this problem yourself.
- When you're done, check the "I have answered this question" box below.
- View the solution and report whether you got it right or wrong.
A file data/trial.csv contains 120 rows and 5 columns. One column, treatment, holds the text values "control", "low", and "high". Another, response, holds measured numbers.
Write the R commands that (a) import the file into an object named trial, (b) confirm the file was parsed into the expected shape, (c) confirm the type of every column, and (d) make treatment behave as a categorical variable with "control" as the reference level. Explain why step (d) is necessary rather than automatic, and how you would verify that no typing error created a fourth category.
Mark Yourself Question
- Grab a piece of paper and try this problem yourself.
- When you're done, check the "I have answered this question" box below.
- View the solution and report whether you got it right or wrong.
Using the data frame trial from the previous setting, with numeric column response and factor column treatment having three levels:
(a) Write a command that returns the mean response for each treatment level. (b) Write a command that returns the standard deviation for each level, and one that returns the number of observations per level. (c) Write a command producing a plot that compares the three groups' distributions. (d) Suppose the three group means come back as 4.2, 5.6, and 6.1. Explain what you can and cannot conclude from those three numbers alone.