There are circumstances when one wants to generate all possible combinations of levels for two factors. For example, factor one with levels ‘A’, ‘B’ and ‘C’, and factor two with levels ‘D’, ‘E’, ‘F’. The function expand.grid()
comes very handy here:
combo <- expand.grid(factor1 = LETTERS[1:3], factor2 = LETTERS[4:6]) combo factor1 factor2 \n1 A D \n2 B D \n3 C D \n4 A E \n5 B E \n6 C E \n7 A F \n8 B F \n9 C F
Omitting the variable names (factor1 and factor 2) will automatically name the variables as Var1 and Var2. Of course we do not have to use letters for the factor levels; if you have defined a couple of factors (say Fertilizer and Irrigation) you can use levels(Fertilizer)
and levels(Irrigation)
instead of LETTERS...
0 Comments
1 Pingback