The expand.grid function

This is a useful function for generating tables of combinations of factor levels. Suppose we have three variables: height with five levels between 60 and 80 in steps of 5, weight with five levels between 100 and 300 in steps of 50, and two sexes.

expand.grid(height = seq(60, 80, 5), weight = seq(100, 300, 50),
sex = c("Male","Female"))

      height    weight       sex
1         60       100      Male
2         65       100      Male
3         70       100      Male
4         75       100      Male
5         80       100      Male
6         60       150      Male
7         65       150      Male
8         70       150      Male
9         75       150      Male
10        80       150      Male
11        60       200      Male
...
47        65       300    Female
48        70       300    Female
49        75       300    Female
50        80       300    Female

Get The R Book now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.