Re: [R] levels of factor when subsetting the factor

From: Peter Dalgaard <p.dalgaard_at_biostat.ku.dk>
Date: Tue 12 Sep 2006 - 15:45:07 GMT

"Afshartous, David" <afshart@exchange.sba.miami.edu> writes:

>
> All,
>
> When I take a subset of a factor the reduced factor still maintains all
> the original levels of the factor when say forming the key in a plot.
> The data is correct, but the variable still "remembers" the original
> levels. See below for reproducible code. Does anyone know how to fix
> this?
> cheers,
> dave
>
> fact = as.factor(c(rep("A", 3),rep("B", 3), rep("C", 3)))
> new.fact = fact[1:6]
> > new.fact
> [1] A A A B B B
> Levels: A B C ## should only show A B

Just use

> factor(new.fact)
[1] A A A B B B
Levels: A B

or

> fact[1:6, drop=T]
[1] A A A B B B
Levels: A B

And, no, it is not a bug. The fact that a subsample happens to consist only of males does not turn gender into a one-level factor... (Apart from the philosophy, it makes a real difference in tabulation.)

-- 
   O__  ---- Peter Dalgaard             ุster Farimagsgade 5, Entr.B
  c/ /'_ --- Dept. of Biostatistics     PO Box 2099, 1014 Cph. K
 (*) \(*) -- University of Copenhagen   Denmark          Ph:  (+45) 35327918
~~~~~~~~~~ - (p.dalgaard@biostat.ku.dk)                  FAX: (+45) 35327907

______________________________________________
R-help@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.
Received on Wed Sep 13 02:05:48 2006

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Tue 12 Sep 2006 - 17:30:05 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.