[R] expand.grid and the first level of a factor

John Fox jfox at mcmaster.ca
Sat May 3 14:54:45 CEST 2003


Dear Giovanni,

At 12:53 PM 5/3/2003 +0000, Giovanni Marchetti wrote:
>I do not understand this behaviour of expand.grid:
>
> > expand.grid(x = c("b", "a"), y = c(1, 2))$x
>[1] b a b a
>Levels: b a
> > expand.grid(x = c("b", "a"))$x
>[1] b a
>Levels: a b
>
>Why the first level of the factor x depends on the number
>of arguments of expand.grid? Apparently, I can set
>the order of the levels only when the number of
>arguments in > 1. In the second example, the order
>is lexicographic.

As the help for expand.grid states, expand.grid generates all combinations 
of values of its arguments. Take a look at the entirety of the result:

 > expand.grid(x = c("b", "a"), y = c(1, 2))
   x y
1 b 1
2 a 1
3 b 2
4 a 2


Compare, for example, to

         expand.grid(x = c("b", "a"), y = c(1, 2), z=c(TRUE, FALSE))

which generates 8 rows.

I hope that this helps,
  John


-----------------------------------------------------
John Fox
Department of Sociology
McMaster University
Hamilton, Ontario, Canada L8S 4M4
email: jfox at mcmaster.ca
phone: 905-525-9140x23604
web: www.socsci.mcmaster.ca/jfox



More information about the R-help mailing list