# [R] FAQ and Answer: How to convert factors back to integers

Peter Dalgaard BSA p.dalgaard at biostat.ku.dk
Tue Feb 15 00:12:45 CET 2000

```rossini at biostat.washington.edu (A.J. Rossini) writes:

> 	as.numeric(levels(hivplasma))[codes(hivplasma)]
^^^^^

Whoops. Make that as.integer(), codes() has some Splus-compatible
breakage built into it:

> f<-factor(1:10)
> f
[1] 1  2  3  4  5  6  7  8  9  10
Levels:  1 2 3 4 5 6 7 8 9 10
> as.numeric(levels(f))[codes(f)]
[1]  1  3  4  5  6  7  8  9 10  2

It happens because 10 sorts between 1 and 2, alphabetically. Yes, it
is silly...

If you're not badly squeezed for space, as.numeric(as.character(f))
works too, and is easier to remember.

--
O__  ---- Peter Dalgaard             Blegdamsvej 3
c/ /'_ --- Dept. of Biostatistics     2200 Cph. N
(*) \(*) -- University of Copenhagen   Denmark      Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)             FAX: (+45) 35327907
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._

```