Re: [Rd] order of levels in interaction()

From: Martin Maechler <>
Date: Fri 01 Dec 2006 - 09:45:15 GMT

>>>>> "BDR" == Prof Brian Ripley <> >>>>> on Thu, 30 Nov 2006 21:48:35 +0000 (GMT) writes:

    BDR> On Thu, 30 Nov 2006, Deepayan Sarkar wrote:
>> Hi,
>> ?interaction says:
>> See Also:
>> 'factor'; ':' where 'f:g' is the similar to
>> 'interaction(f, g, sep=":")' when 'f' and 'g' are
>> factors.
>> This is not quite true (or maybe 'similar' is the
>> operative word), since:

    >>> f <- factor(1:3); g <- factor(letters[1:3])
    >>> levels(f:g)

>> [1] "1:a" "1:b" "1:c" "2:a" "2:b" "2:c" "3:a" "3:b" "3:c"
>>> levels(interaction(f, g, sep = ":"))

>> [1] "1:a" "2:a" "3:a" "1:b" "2:b" "3:b" "1:c" "2:c" "3:c"
>> Note the different order of the levels. I like the order
>> in f:g better (and at least one other person agrees [1]
>> ), but I also want the flexibility of having a 'sep'
>> argument. Would it be possible to change interaction to
>> allow this? A simple fix that makes interaction behave
>> like ":" is to replace

    BDR> No, for it also says

    BDR>       The levels are ordered so the level of the first
    BDR> factor varies fastest, then the second and so on.  This
    BDR> is the reverse of lexicographic ordering, and differs
    BDR> from ':'.  (It is done this way for compatibility with S.)

    BDR> and reversing it would break things. (It does, I tried     BDR> it a while back.)

yes, indeed {{ and Deepayan should have ... :-) .. }}

But instead of having Deepayan and other users write their own customized version of interaction() and having interaction2() end up in one of those CRAN packages ( ;-} ), we could add a new argument to interaction() which allows the new behavior - not active by default, of course.

I'm happy to do this; the only question remaining is how the argument should be called, and if it's sufficient to have it logical, or if there are more variations that should be considered (I think not).

My quick proposals (name and default):

    reverse = FALSE
    orderFirst = FALSE

>> as.vector(outer(l, lvs, paste, sep = sep))
>> with
>> as.vector(t(outer(l, lvs, paste, sep = sep)))
>> in interaction.
>> -Deepayan
>> [1]

Martin mailing list Received on Sat Dec 02 03:50:40 2006

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Fri 01 Dec 2006 - 17:30:49 GMT.

Mailing list information is available at Please read the posting guide before posting to the list.