Handy R Function: expand.grid

In graduate school I took an experimental design class. As expected, we were assigned a group project that required us to design and analyze our own experiment. Two other students and I got together and decided to design an experiment involving paper airplanes. Not terribly useful, but it’s not as if we had a grant from the NSF. Anyway, we wanted to see what caused a plane to fly farther. Was it design? Was it paper weight? Was it both? We ended up running a 3 x 3 factorial experiment with the paper airplane throwers (us) as blocks.

We had three different paper airplane designs, three different paper weights, three people throwing, and replications. If memory serves, replications was three. In other words, each of us threw each of the 9 airplanes ( 3 designs x 3 paper weights) three times. That came out to 81 throws.

Now we had to randomly pick an airplane and throw it. How to randomize? Here’s a handy way to do that in R. First we use the expand.grid function. This creates a data frame from all combinations of  factors:

d <- expand.grid(throw=c(1,2,3), 
                      design=c(1,2,3), 
                      paper=c(20,22,28), 
                      person=c("Jack","Jane","Jill"))
head(d)
 throw design paper person
1 1 1 20 Jack
2 2 1 20 Jack
3 3 1 20 Jack
4 1 2 20 Jack
5 2 2 20 Jack
6 3 2 20 Jack

We see Jack will throw design 1 made of 20 lb. paper three times. Then he'll throw design 2 made of 20 lb. paper three times. And so on. Now to randomly sort the data frame:

d_rand <- d[sample(1:nrow(d)),]
d_rand
 throw design paper person
34 1 3 20 Jane
20 2 1 28 Jack
3 3 1 20 Jack
53 2 3 28 Jane
37 1 1 22 Jane
77 2 2 28 Jill

Very handy! And nifty, too.

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.