From savicky at cs.cas.cz  Fri May  8 17:14:48 2009
From: savicky at cs.cas.cz (Petr Savicky)
Date: Fri, 8 May 2009 17:14:48 +0200
Subject: [Rd] suggestion for extending ?as.factor
In-Reply-To: <18948.12553.265256.981657@lynne.math.ethz.ch>
References: <20090503203204.GB29507@cs.cas.cz>
	<18942.43500.862186.878365@lynne.math.ethz.ch>
	<49FEEED1.8000808@biostat.ku.dk>
	<18943.3144.768738.188706@lynne.math.ethz.ch>
	<20090504163403.GA10640@cs.cas.cz> <49FF25A6.3070907@biostat.ku.dk>
	<18943.64094.648164.476070@lynne.math.ethz.ch>
	<18945.19798.782710.936788@lynne.math.ethz.ch>
	<20090508090155.GA18486@cs.cas.cz>
	<18948.12553.265256.981657@lynne.math.ethz.ch>
Message-ID: <20090508151448.GA6692@cs.cas.cz>

On Fri, May 08, 2009 at 03:18:01PM +0200, Martin Maechler wrote:
> As long as we don't want to allow  factor(<numeric>) to fail --rarely -- 
> I think (and that actually has been a recurring daunting thought
> for quite a few days) that we probably need an
> extra step of checking for duplicate levels, and if we find
> some, recode "everything". This will blow up the body of the
> factor() function even more.
> 
> What alternatives do you (all R-devel readers!) see?

The command 
  f <- match(x, levels)
in factor() uses the original values and not their string representations.
I think that the main reason to do so is that we loose the ordering, if the
conversion to character is done before levels are sorted.

Let me suggest to consider the following modification, where match() is done
on the strings, not on the original values.
  levels <- unique(as.character(sort(unique(x))))
  x <- as.character(x)
  f <- match(x, levels)

Since unique() preserves the order, we will get the levels correctly
ordered. Due to using unique() twice, we will not have duplicated levels.

Is it correct?

Petr.



[Rd] suggestion for extending ?as.factor
Petr Savicky