From savicky at cs.cas.cz  Fri May  8 18:10:56 2009
From: savicky at cs.cas.cz (Petr Savicky)
Date: Fri, 8 May 2009 18:10:56 +0200
Subject: [Rd] suggestion for extending ?as.factor
In-Reply-To: <20090508151448.GA6692@cs.cas.cz>
References: <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>
	<20090508151448.GA6692@cs.cas.cz>
Message-ID: <20090508161056.GB6692@cs.cas.cz>

On Fri, May 08, 2009 at 05:14:48PM +0200, Petr Savicky wrote:
> 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)

An alternative solution is
  ind <- order(x)
  x <- as.character(x) # or any other conversion to character
  levels <- unique(x[ind]) # get unique levels ordered by the original values
  f <- match(x, levels)

The advantage of this over the suggestion from my previous email is that
the string conversion is applied only once. The conversion need not be only
as.character(). There may be other choices specified by a parametr. I have
strong objections against the existing implementation of as.character(),
but still i think that as.character() should be the default for factor()
for the sake of consistency of the R language.

Petr.



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