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

Uwe Ligges ligges at statistik.uni-dortmund.de
Sat May 3 15:23:59 CEST 2003

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.
> -- Giovanni

It depends on the number of arguments, because of the implementation 
(look into the code):

In principle, expand.grid(x = c("b", "a")) does the following:

  x <- c("b", "a")

whereas for expand.grid(x = c("b", "a"), y = c(1, 2)), the levels will 
be specified as in:

  factor(x, levels = unique(x))

Hence the difference.

Uwe Ligges

More information about the R-help mailing list