[R] Levels in returned data.frame after subset

Ista Zahn izahn at psych.rochester.edu
Sat Sep 4 15:41:57 CEST 2010


Hi Ulrik

On Sat, Sep 4, 2010 at 12:52 PM, Ulrik Stervbo <ulrik.stervbo at gmail.com> wrote:
> Dear List,
>
> When I subset a data.frame, the levels are not re-adjusted (see
> example). Why is this? Am I missing out on some basic stuff here?

Only that this issue has come up many times before, and that this list
is archived and searchable. Try

RSiteSearch("subset drop levels", restrict = c("Rhelp10", "Rhelp08", "Rhelp02"))


-Ista

>
> Thanks
> Ulrik
>
>
>> m <- data.frame(gender = c("M", "M","F"), ht = c(172, 186.5, 165), wt = c(91,99, 74))
>> dim(m)
> [1] 3 3
>
>> levels(m$gender)
> [1] "F" "M"
>
>> s <- subset(m, m$gender == "M")
>> dim(s)
> [1] 2 3
>
>> levels(s$gender)
> [1] "F" "M"
>
>> cat <- sapply(s, is.factor); s[cat] <- lapply(s[cat], factor)
>> dim(s)
> [1] 2 3
>
>> levels(s$gender)
> [1] "M"
>
> ______________________________________________
> 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.
>



-- 
Ista Zahn
Graduate student
University of Rochester
Department of Clinical and Social Psychology
http://yourpsyche.org



More information about the R-help mailing list