[R] Obtaining the internal integer codes of a factor XXXX

William Dunlap wdunlap at tibco.com
Mon Mar 25 17:50:52 CET 2013


I would like to add that using the labels argument without a levels
argument in factor(),
   fdata<-factor(c("b","b","c","a","b","c"),labels=c("I","II","III"))
is a dangerous way to make your factor.

Consider what would happen if the 4th input value were not "a" but
was "d" or if you were in a locale where the sort order is not "a", "b",
"c" (this is unlikely in this example, but if you had some capitalized and
some not the sort order would be different in the "C" locale and almost
any other locale).

Avoid the problem by stating what the input levels are expected to be:
   fdata <- factor( c("b","b","c","a","b","c"), levels=c("a","b","c"), labels=c("I","II","III"))

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com


> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf
> Of Rui Barradas
> Sent: Monday, March 25, 2013 9:38 AM
> To: Dan Abner
> Cc: r-help at r-project.org
> Subject: Re: [R] Obtaining the internal integer codes of a factor XXXX
> 
> Hello,
> 
> Though I have the same doubt as Bert, the following seems to make more
> sense.
> 
> seq_along(levels(fdata))
> 
> 
> Hope this helps,
> 
> Rui Barradas
> 
> Em 25-03-2013 15:37, Dan Abner escreveu:
> > Hi everyone,
> >
> > I understand the process of obtaining the internal integer codes for
> > the raw values of a factor (using as.numeric() as below), but what is
> > the best way to obtain these codes for the levels() of a factor (since
> > the as.numeric() results don't really make clear which code maps to
> > which level)?
> >
> >
> > fdata<-factor(c("b","b","c","a","b","c"),labels=c("I","II","III"))
> > fdata
> > levels(fdata)
> >
> > as.numeric(fdata)
> >
> >
> > I thought something like this would make sense and work, but it throws an error:
> >
> > as.numeric(levels(fdata))
> >
> > Thanks!
> >
> > Dan
> >
> > ______________________________________________
> > 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.
> >
> 
> ______________________________________________
> 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.



More information about the R-help mailing list