[R] strings as factors

Bill.Venables at csiro.au Bill.Venables at csiro.au
Tue Dec 12 04:30:33 CET 2006


Here is a possibility:

> test <- expand.grid(id = 1:2, sex = c('male', 'female'))
> sapply(test, class)
       id       sex 
"integer"  "factor" 
> test <- transform(test, sex = as.character(sex))
> sapply(test, class)
         id         sex 
  "integer" "character" 


But I am surprised at the reason you give for needing it as a character
vector, because factors often act as character vectors under matching
anyway.

> sexf <- factor(test[[2]])
> sexf
[1] male   male   female female
Levels: female male

> which(sexf %in% "male")
[1] 1 2
> which(sexf == "male")
[1] 1 2

Bill Venables
 

-----Original Message-----
From: r-help-bounces at stat.math.ethz.ch
[mailto:r-help-bounces at stat.math.ethz.ch] On Behalf Of Alexander Nervedi
Sent: Tuesday, 12 December 2006 10:09 AM
To: r-help at stat.math.ethz.ch
Subject: [R] strings as factors

Hi,
To be able to match cases with a benchmark I need to have a data.frame
with 
a character id variable. however, I am surprised why this seems to be so

hard. In fact I was  unable to succeed. Here is what I tried:

>test1 <-expand.grid(ID = 1:2, sex = c("male","female"))
>is(test1[,2])
[1] "factor"   "oldClass"
>test2 <-expand.grid(ID = 1:2, sex = c('male','female'))
>is(test2[,2])
[1] "factor"   "oldClass"
>test3 <-expand.grid(ID = 1:2, sex = I(c("male","female")))
>is(test3[,2])
[1] "factor"   "oldClass"
>test4 <-expand.grid(ID = 1:2, sex = I(c('male','female')))
>is(test4[,2])
[1] "factor"   "oldClass"
>options(stringsAsFactors = FALSE)
>options("stringsAsFactors")
$stringsAsFactors
[1] FALSE

>test5 <-expand.grid(ID = 1:2, sex = I(c('male','female')))
>is(test5[,2])
[1] "factor"   "oldClass"


is there anyway I can get sex to be a character?

Arnab

_________________________________________________________________
Visit MSN Holiday Challenge for your chance to win up to $50,000 in
Holiday

______________________________________________
R-help at stat.math.ethz.ch 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.




More information about the R-help mailing list