[R] numeric to factor via lookup table

Bert Gunter gunter.berton at gene.com
Fri Mar 28 21:56:25 CET 2014


Note that your example may be misleadingly simple, so I made it a bit
more complicated.

The key is ?match

> mylevels <- data.frame(ID=10:1,code=letters[1:10])
> values <- c(1,2,5,5,10)
> with(mylevels,code[match(values,ID)])
[1] j i f f a
Levels: a b c d e f g h i j

## Note that you may have to take care if there are NA's in values.
Read ?match carefully if this might happen.

Cheers,
Bert


>

Bert Gunter
Genentech Nonclinical Biostatistics
(650) 467-7374

"Data is not information. Information is not knowledge. And knowledge
is certainly not wisdom."
H. Gilbert Welch




On Fri, Mar 28, 2014 at 1:38 PM, Jonathan Greenberg <jgrn at illinois.edu> wrote:
> R-helpers:
>
> Hopefully this is an easy one.  Given a lookup table:
>
> mylevels <- data.frame(ID=1:10,code=letters[1:10])
>
> And a set of values (note these do not completely cover the mylevels range):
>
> values <- c(1,2,5,5,10)
>
> How do I convert values to a factor object, using the mylevels to
> define the correct levels (ID matches the values), and code is the
> label?
>
> --j
>
> --
> Jonathan A. Greenberg, PhD
> Assistant Professor
> Global Environmental Analysis and Remote Sensing (GEARS) Laboratory
> Department of Geography and Geographic Information Science
> University of Illinois at Urbana-Champaign
> 259 Computing Applications Building, MC-150
> 605 East Springfield Avenue
> Champaign, IL  61820-6371
> Phone: 217-300-1924
> http://www.geog.illinois.edu/~jgrn/
> AIM: jgrn307, MSN: jgrn307 at hotmail.com, Gchat: jgrn307, Skype: jgrn3007
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.




More information about the R-help mailing list