[R] converting a factor in numeric values with direct control of the numeric values
Charles C. Berry
cberry at tajo.ucsd.edu
Sat Jan 17 18:12:39 CET 2009
On Sat, 17 Jan 2009, Jörg Groß wrote:
> 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
Like this:
> z <- c("male", "male", "female")
> z <- as.factor(z)
> num.codes[ levels(z) ][ z ]
male male female
3 3 5
>
or if you want to avoid the names():
> z.to.num <- unname(num.codes)[ match(levels(z),names(num.codes)) ]
> z.to.num[ z ]
[1] 3 3 5
>
See
?as.character
?match
?levels
HTH,
Chuck
>
>
> Thanks for any help!
>
> ______________________________________________
> 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.
>
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
More information about the R-help
mailing list