[R] reduce levels

Bill.Venables@csiro.au Bill.Venables at csiro.au
Tue Nov 8 03:11:39 CET 2005


sub$mm <- factor(sub$mm)

is the simplest way to change a single factor in this way.  To do a
whole data frame you just need a loop:

drop_unused_levels <- function(data) 
	as.data.frame(lapply(data, function(x) if(is.factor(x))
factor(x) else x ))

Here's your example again, but witn a slightly different idiom...

test <- data.frame(mm = letters[1:3])
sub <- subset(test, mm == "b")

fixedSub <- drop_unused_levels(sub)

Bill Venables.

-----Original Message-----
From: r-help-bounces at stat.math.ethz.ch
[mailto:r-help-bounces at stat.math.ethz.ch] On Behalf Of Claus Atzenbeck
Sent: Tuesday, 8 November 2005 9:52 AM
To: R-help
Subject: [R] reduce levels


Hi all:

I have an example that shows my problem:

    > test <- data.frame(c("a", "b", "c"))
    > colnames(test) <- "mm"
    > sub <- subset(test, mm=="b")
    > sub$mm
    [1] b
    Levels: a b c
    > levels(sub$mm)
    [1] "a" "b" "c"

How can I reduce the levels to exclusively those which are part of the
data frame? That is in the above named example exclusively "b".

Reason: I want to iterate exclusively through those levels that exist
within a subset, but leave away all others.

Thanks for any hint.
Claus

______________________________________________
R-help at 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




More information about the R-help mailing list