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

From: Sarah Goslee <sarah.goslee_at_gmail.com>
Date: Wed, 18 Mar 2009 11:33:17 -0400

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

______________________________________________
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.
Received on Wed 18 Mar 2009 - 14:37:39 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Wed 18 Mar 2009 - 15:30:28 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive