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 -- < Giovanni M. Marchetti > Dipartimento di Statistica, Univ. di Firenze Phone: +39 055 4237 204 viale Morgagni, 59 Fax: +39 055 4223 560 I 50134 Firenze, Italy email: gmm at ds.unifi.it
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
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. > > -- GiovanniIt 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") factor(x) 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