[R] Numeric to factor

Göran Broström gb at stat.umu.se
Wed Oct 9 08:22:12 CEST 2002


On Tue, 8 Oct 2002, Thomas Lumley wrote:

> On Tue, 8 Oct 2002, [iso-8859-1] Göran Broström wrote:
>
> > I find 'How do I convert factors to numeric?' in the FAQ (7.12), but not
> > the other way around. Trivial maybe, but
> >
> > > codes(factor(c(2, 10))
> > [1] 2 1
> > > codes(factor(c(2, 9)))
> > [1] 1 2
> >
> > How do I get the levels attached to the codes in numeric order?
> >
>
> The short answer is that you don't. If you care about the order of the
> codes then you have an ordered factor
> >  codes(ordered(c(2, 10)))
> [1] 1 2
> >  codes(ordered(c(2, 9)))
> [1] 1 2
>
> As the code for codes.factor is
> function (x, ...)
> {
>     rank(levels(x))[x]
> }
> you can't change the order from the default, lexicographic order.
>
> Perhaps your problem is that you think codes() means something (eg the
> numbers used internally to code the factor).

Yes. I thought I would get the internal codes, as for an ordered factor.
In fact, I wasn't interested in factors per se; my problem is that I have
a data frame with one column of IDs (each nine digits long), and I want
new IDs numbered 1, 2, 3, ...., preserving the original order. The reason
for that is that I then can index other variables with the IDs and write
some smart functions. I tried

> new.id <- codes(factor(old.id))

but  discovered that order (the one I wanted)was not preserved. As some
respondents have explained,

> new.id <- as.integer(factor(old.id))

does the trick (BTW, is this the best way to do what I want?).
Thanks to all who responded.

Göran

>
> This may be illuminating:
> > unclass(factor(c(2,9)))
> [1] 1 2
> attr(,"levels")
> [1] "2" "9"
> > unclass(factor(c(2,10)))
> [1] 1 2
> attr(,"levels")
> [1] "2"  "10"
> > as.integer(factor(c(2,9)))
> [1] 1 2
> > as.integer(factor(c(2,10)))
> [1] 1 2
> >
>
> 	-thomas
>
>
>

---
 Göran Broström                    tel: +46 90 786 5223
 Department of Statistics          fax: +46 90 786 6614
 Umeå University                   http://www.stat.umu.se/egna/gb/
 SE-90187 Umeå, Sweden             e-mail: gb at stat.umu.se


-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list