[R] numeric to factor via lookup table
    Marc Schwartz 
    marc_schwartz at me.com
       
    Fri Mar 28 22:00:40 CET 2014
    
    
  
On Mar 28, 2014, at 3: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
One approach would be to use ?merge and specify the 'by.*' arguments using column indices, where 'values' is column 1 and you want to match that with mylevels$ID, which is also column 1. Hence:
> merge(values, mylevels, by.x = 1, by.y = 1)
   x code
1  1    a
2  2    b
3  5    e
4  5    e
5 10    j
Regards,
Marc Schwartz
    
    
More information about the R-help
mailing list