[R] factor always have type integer

Erich Neuwirth erich.neuwirth at univie.ac.at
Wed Sep 8 21:52:26 CEST 2004

typeof applied to a factor always seems to return "integer",
independently of the type of the levels.
This has a strange side effect.
When a variable is "imported" into a data frame,
its type changes.
character variables automatically are converted
to factors when imported into data frames.

Here is an example:

 > v1<-1:3
 > v2<-c("a","b","c")
 > df<-data.frame(v1,v2)
 > typeof(v2)
[1] "character"
 > typeof(df$v2)
[1] "integer"

It is somewhat surprising that
the types of v2 and df$v2 are different.

the answer is to do
but that is somewhat involved.

Should the types not be identical, and typeof applied to factors
return the type of the levels?

Erich Neuwirth, Computer Supported Didactics Working Group
Visit our SunSITE at http://sunsite.univie.ac.at
Phone: +43-1-4277-38624 Fax: +43-1-4277-9386

More information about the R-help mailing list