[R] coercing "numeric" components of data frame to "factor" or "ordered"?

John Fox jfox at mcmaster.ca
Fri May 3 03:03:33 CEST 2002

Dear Russell,

At 02:45 PM 5/2/2002 -0700, you wrote:

>I am getting ready to load a bunch of data into R.  The data is all
>numeric, but some of the numbers are integer codes representing
>non-numeric semantics.  What is the best way to "fix" the data frames
>so that these compenents are recognized as "factors" or "ordered", as
>Can I "assign" to some attribute of the data frame component, like the
>"class" or "levels" to get the desired effect?

Actually, you can do exactly what you suggest. Say you have a data frame df 
with numeric variables one and two:

         attr(df$one, 'levels') <- sort(unique(df$one))
         class(df$one) <- 'factor'

         attr(df$two, 'levels') <- sort(unique(df$two))
         class(df$two) <- c('ordered', 'factor')

But it's probably simpler just to do

         df$one <- factor(df$one)
         df$two <- ordered(df$two)

I hope that this helps,

John Fox
Department of Sociology
McMaster University
Hamilton, Ontario, Canada L8S 4M4
email: jfox at mcmaster.ca
phone: 905-525-9140x23604
web: www.socsci.mcmaster.ca/jfox

r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch

More information about the R-help mailing list