Skip to content
Prev 199757 / 398506 Next

drop unused levels in subset.data.frame

On Nov 10, 2009, at 10:49 AM, baptiste auguie wrote:

            
If you are looking for a one-liner, then consider:

data.frame(lapply(s, function(x) if (is.factor(x)){ factor(x)} else  
{x}))

I added a numeric column to make sure I had not clobbered a non-factor  
variable.

 > d <- data.frame(x = factor(letters[1:15]), y =  
factor(LETTERS[1:3]), N=1:15)
 > s <- subset(d, y=="A", drop=TRUE)
 > str( data.frame(lapply(s, function(x) if (is.factor(x)){ factor(x)}  
else {x})) )
'data.frame':	5 obs. of  3 variables:
  $ x: Factor w/ 5 levels "a","d","g","j",..: 1 2 3 4 5
  $ y: Factor w/ 1 level "A": 1 1 1 1 1
  $ N: int  1 4 7 10 13
David Winsemius, MD
Heritage Laboratories
West Hartford, CT