[R] factor question

Mark Difford mark_difford at yahoo.co.uk
Thu Jul 24 22:07:40 CEST 2008


Hi Edna,

Because I am "always" subsetting, I keep the following function handy

mydata[] <- lapply(mydata, function(x) if(is.factor(x)) x[,drop=T] else x)

This will strip out all factor levels that have been dropped by a previous
subsetting operation. For novice users of R (though I am not suggesting that
you are) it's priceless.

The original author, as far as I know, is Andy Liaw (author of the
randomForest package).

HTH, Mark.


Edna Bell wrote:
> 
> Hi!
> 
> Suppose I have a factor:
> 
>> fac1 <- factor(rep(c("dog","cat","tree"),c(2,3,4)))
>> fac1
> [1] dog  dog  cat  cat  cat  tree tree tree tree
> Levels: cat dog tree
>> length(fac1)
> [1] 9
> 
> Now I want to get rid of the dogs:
>> fac1 <- fac1[3:9]
>> fac1
> [1] cat  cat  cat  tree tree tree tree
> Levels: cat dog tree
>>
> How should I remove the dog from the level, please?
> 
> Thanks in advance,
> Edna Bell
> 
> ______________________________________________
> 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.
> 
> 

-- 
View this message in context: http://www.nabble.com/factor-question-tp18638814p18639010.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list