Factors, Grouping and Tables: tapply, aggregate and cut
Turn text into factors, count categories with table, compute statistics per group with tapply and aggregate, bin numbers with cut, and verify the group means in Python.
In this lesson you will
- Create factors and set level order
- Count with table
- Compute statistics per group
- Bin numbers with cut
About 28 minutes
Does the fertiliser group matter?
Nia’s main question is about groups: are the plants that got fertiliser taller than those that did not? To answer it, R needs to know that “control”, “organic” and “chemical” are categories and not arbitrary text. A factor is a vector of categories with a fixed set of allowed values, called levels. By default levels are sorted alphabetically, which puts “chemical” before “control”, so Nia sets the order she wants with the levels argument. A factor stores each value as a small integer code and the labels once, which saves memory and makes grouping fast, and it prevents typos such as “Control” from creating a fourth group by accident.
Three functions handle most grouping. table counts how many observations fall in each category, or each combination of two. tapply applies a function to a vector separately for each level of a factor, returning a named vector. aggregate does the same for a data frame with a formula such as height ~ group, and returns a data frame, which is the easiest to print and save. cut turns a numeric variable into categories using breakpoints, which gives the classic “short, medium, tall” bands.
| Function | Result |
|---|---|
| factor(x, levels = …) | Categories in a chosen order |
| table(f) | Counts per level |
| tapply(x, f, mean) | Named vector of group means |
| aggregate(y ~ f, df, mean) | Data frame of group means |
| cut(x, breaks, labels) | Numbers turned into bands |
plants <- data.frame(
group = rep(c("control", "organic", "chemical"), each = 4),
height = c(12.1, 13.4, 11.8, 12.9, 15.2, 16.8, 14.9, 15.7, 18.3, 17.5, 19.1, 18.8)
)
plants$group <- factor(plants$group, levels = c("control", "organic", "chemical"))
cat("levels:", levels(plants$group), "| as integers:", as.integer(plants$group), "\n")
print(table(plants$group))
means <- tapply(plants$height, plants$group, mean)
cat("tapply means:", paste(names(means), round(means, 3), collapse = ", "), "\n")
sds <- tapply(plants$height, plants$group, sd)
cat("tapply sds:", paste(names(sds), round(sds, 4), collapse = ", "), "\n")
agg <- aggregate(height ~ group, data = plants, FUN = mean)
print(agg)
band <- cut(plants$height, breaks = c(0, 14, 17, Inf), labels = c("short", "medium", "tall"))
print(table(band))
print(table(plants$group, band))
cat("overall mean:", mean(plants$height), "| organic minus control:", round(means["organic"] - means["control"], 3), "\n")
oops <- factor(c("control", "Control", "organic"))
cat("a typo made", nlevels(oops), "levels:", levels(oops), "\n")
levels: control organic chemical | as integers: 1 1 1 1 2 2 2 2 3 3 3 3
control organic chemical
4 4 4
tapply means: control 12.55, organic 15.65, chemical 18.425
tapply sds: control 0.7326, organic 0.8347, chemical 0.6994
group height
1 control 12.550
2 organic 15.650
3 chemical 18.425
band
short medium tall
4 4 4
band
short medium tall
control 4 0 0
organic 0 4 0
chemical 0 0 4
overall mean: 15.54167 | organic minus control: 3.1
a typo made 3 levels: control Control organic
The factor call fixed the order of the levels to control organic chemical and stored each plant as a small integer code, 1 1 1 1 2 2 2 2 3 3 3 3, while the labels are kept once. The table counted four plants per group, 4, 4 and 4, which is the balanced design Nia wanted. The last two lines of the program show why factors matter: the typo “Control” with a capital letter created a third level, giving 3 levels (control Control organic) instead of two, and a factor with a fixed set of levels makes such a mistake visible instead of splitting a group silently.
The statistics per group answer the question. The tapply function gave the means control 12.55, organic 15.65, chemical 18.425, and the standard deviations control 0.7326, organic 0.8347, chemical 0.6994. The aggregate call produced the same means as a small data frame, easier to print or save. The organic group is 3.1 centimetres taller than the control group on average, and the chemical group is taller still. The overall mean of the twelve plants is 15.54167.
The cut function put each height into a band with breaks at 14 and 17, where each band includes its upper limit: 4 short plants (up to 14), 4 medium (above 14 up to 17) and 4 tall (above 17). The two-way table of group by band shows how the bands split over the groups: all four control plants are short, and all four chemical plants are tall, and all four organic plants are medium, so in this small experiment the groups do not overlap at all.
Independent check: Python grouped the same twelve heights by hand and computed the three group means and sample standard deviations, and counted the heights in each band, and all of them match R to the digits shown. Be careful about one detail: cut includes the upper boundary by default, so a height of exactly 14 would be short. You can change that with right = FALSE.
Check by hand: the control group is 12.1, 13.4, 11.8 and 12.9, which add up to 50.2, so the mean is 12.55. The organic group adds up to 62.6, so its mean is 15.65, and the chemical group adds up to 73.7, with a mean of 18.425. The difference between organic and control is 15.65 minus 12.55, which is 3.1.
Alphabetical level order puts “chemical” first. Models and tables use the first level as the reference, so set the order explicitly when it matters, for example with the control group first.
tapply returns a named vector, which is fine for a quick look. aggregate returns a data frame with the group as a column, which you can write to a file or merge with other tables.
Every program in this lesson was run with R 4.3.3 using Rscript –vanilla (base R only, no packages) while the course was written. R releases new versions every year, so check r-project.org for the current version and for any change in behaviour.
Practice
Compute the median per group with tapply. Use cut with right = FALSE and compare the bands. Use aggregate with cbind(height, leaves) ~ group to get two means per group in one table.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
What is a factor?
- A vector of categories with fixed levels
- A number
- A plot
- A function
Stored as integer codes with labels.
What does tapply(x, g, mean) return?
- A data frame
- A plot
- The overall mean
- A named vector of group means
aggregate returns a data frame instead.
What does table(f) do?
- Sorts the factor
- Draws a table
- Deletes duplicates
- Counts observations per category
Two factors give a two-way table.
What does cut do?
- Deletes rows
- Cuts a vector in half
- Turns numbers into bands
- Splits a string
It uses breakpoints.
Why set the levels of a factor explicitly?
- To save memory only
- To sort the data frame
- To control the order, such as the reference group
- It is required
The default is alphabetical.
Summary
- Factors hold categories with a fixed set of levels.
- table counts, tapply and aggregate summarise per group, cut makes bands.
- Set the level order explicitly when the reference group matters.
- Group means and standard deviations were confirmed in Python.
Questions
Factor or character?
Use a factor for a variable with a small set of categories that you group by or model. Use character for free text such as names and comments.
How do I drop unused levels?
With droplevels(f) after you subset a data frame, otherwise the empty levels still appear in tables.
Can aggregate use several functions?
Pass one function at a time, or a function that returns a vector, such as function(x) c(mean = mean(x), sd = sd(x)), and check the shape of the result.
