[R] Please help! How do I change the class of a numeric variable in a grouped data object to a factor?

Sarah Goslee sarah.goslee at gmail.com
Wed Mar 18 16:33:17 CET 2009


Well, it would have helped if you'd given us an example of what
exactly you did, but here's a working solution.

> Orthodont <- data.frame(age = 1:6, sex = factor(c("m", "f", "m", "f", "m", "f")))
> str(Orthodont)
'data.frame':	6 obs. of  2 variables:
 $ age: int  1 2 3 4 5 6
 $ sex: Factor w/ 2 levels "f","m": 2 1 2 1 2 1
> Orthodont$age <- factor(Orthodont$age)
> str(Orthodont)
'data.frame':	6 obs. of  2 variables:
 $ age: Factor w/ 6 levels "1","2","3","4",..: 1 2 3 4 5 6
 $ sex: Factor w/ 2 levels "f","m": 2 1 2 1 2 1
> Orthodont$sex <- c(1, -1)[as.numeric(Orthodont$sex)]
> str(Orthodont)
'data.frame':	6 obs. of  2 variables:
 $ age: Factor w/ 6 levels "1","2","3","4",..: 1 2 3 4 5 6
 $ sex: num  -1 1 -1 1 -1 1


Note that the last one depends on the ordering of your male and
female factors. Here "f" is 1 and "m" is 2, so I used c(1, -1) - the
desired values for "f" and "m" in numeric order by factor.

Sarah

On Mon, Mar 16, 2009 at 5:55 AM, Katya Mauff <Katya.Mauff at uct.ac.za> wrote:
> Hi all
>
> I’m in desperate need of help. I’m working with a grouped data object, called Orthodont in the nlme package in R, and am trying to fit various models (learning methods for my thesis), but one of the variables in the object is numeric, (age) and I need it to be a factor. I’ve tried: as.factor(Orthodont$age)
> as.factor(as.character(Orthodont$age))
>
> and various other things, but when I then check the class of the variables using
> sapply(Orthodont, data.class)
> I still get age as numeric…
>
> Also, sex is a factor, but for the models I’m fitting I need it to be coded as a binary variable with values (-1) for males and (+1) for females, and I don’t know how to do this either. Please help-I’m losing my mind….!
>
>
>
-- 
Sarah Goslee
http://www.functionaldiversity.org




More information about the R-help mailing list