[R] REmove level with zero observations

Erik Iverson eriki at ccbr.umn.edu
Tue Aug 3 23:01:40 CEST 2010



GL wrote:
> If I have a column with 2 levels, but one level has no remaining
> observations. Can I remove the level? 

What is a 'column'?  An element of a data.frame?

Does the following help?

f1 <- factor("L1", levels = c("L1", "L2"))
levels(f1)
f1 <- factor(f1)
levels(f1)

In absence of a reproducible example, as the posting guide requests, I 
cannot tell exactly what you're after here.

> 
> Had intended to do it as listed below, but soon realized that even though
> there are no observations, the level is still there. 
> 
> For instance
> 
> summary(dbs3.train.sans.influential.obs$HAC) 
> 
> yields
> 
> 0 ,1 
> 4685,0 
> 
> nlevels(dbs3.train.sans.influential.obs$HAC)
> 
> yields
> [1] 2
> 
> drop.list <- NULL
> for (i in 1:ncol(dbs3.train.sans.influential.obs)) {       
>      if (nlevels(dbs3.train.sans.influential.obs[,i]) < 2) {drop.list <-
> cbind(drop.list,i)}}
> 
> yields 
> nothing because HAC still has two levels, even though there aren't any
> observations in on of the levels.
> 
> What I want to do is loop through all columns that are factors and create a
> list of items to drop because there will subsequently be < 2 levels when I
> try to run a linear model.
> 
>



More information about the R-help mailing list