Skip to content

converting a factor in numeric values with direct control of the numeric values

7 messages · Jörg Groß, ronggui, David Winsemius +2 more

#
Hi,

I know how to convert a factor-variable into a numeric variable via  
as.numeric().

But how can I control the values that are assigned?


For example, I have this factor-variable:


z <- c("male", "male", "female")
z <- as.factor(z)


And I want to convert male in 3 and female into the numeric value 5  
(just for the example)

so that I get:

[1] 3 3 5


Thanks for any help!
#
I think you have to recode the derived variable of as.numeric(z).
On Sun, Jan 18, 2009 at 12:40 AM, J?rg Gro? <joerg at licht-malerei.de> wrote:

  
    
#
BTW, a better  way to convert factor into a numeric variable is to use
unclass().
On Sun, Jan 18, 2009 at 12:40 AM, J?rg Gro? <joerg at licht-malerei.de> wrote:

  
    
#
On Sat, 17 Jan 2009, J?rg Gro? wrote:

            
Like this:
male   male female
      3      3      5
or if you want to avoid the names():
[1] 3 3 5
See

 	?as.character
 	?match
 	?levels

HTH,

Chuck
Charles C. Berry                            (858) 534-2098
                                             Dept of Family/Preventive Medicine
E mailto:cberry at tajo.ucsd.edu	            UC San Diego
http://famprevmed.ucsd.edu/faculty/cberry/  La Jolla, San Diego 92093-0901
#
ifelse is your friend:

 > z <- c("male", "male", "female")
 >  z <- as.factor(z)
 >
 >  z <- ifelse(z == "male", 3, 5)

 > z
[1] 3 3 5
 > class(z)
[1] "numeric"
 >

--  
David Winsemius
On Jan 17, 2009, at 11:40 AM, J?rg Gro? wrote:

            
#
On Sat, 17 Jan 2009, Charles C. Berry wrote:

            
Oops! I forgot to copy this line
Charles C. Berry                            (858) 534-2098
                                             Dept of Family/Preventive Medicine
E mailto:cberry at tajo.ucsd.edu	            UC San Diego
http://famprevmed.ucsd.edu/faculty/cberry/  La Jolla, San Diego 92093-0901
#
ronggui wrote:
The easiest way is probably to use indexing:

 > z <- c("male", "male", "female")
 > z <- factor(z)
 > c(5,3)[z]
[1] 3 3 5

or, slightly more foolproof

 > c(male=3,female=5)[as.character(z)]
   male   male female
      3      3      5