[R] Expand DF with all levels of a variable

Patrick Hausmann patrick.hausmann at uni-bremen.de
Tue Jun 14 13:32:34 CEST 2011


Dear list,

I would like to expand a DF with all the missing levels of a variable.

a <- c(2,2,3,4,5,6,7,8,9)
a.cut <- cut(a, breaks=c(0,2,6,9,12), right=FALSE )
(x <- data.frame(a, a.cut))

# In 'x'  the level "[0,2)" is "missing".

AddMissingLevel <- function(xdf) {

     xfac <- factor( c("[0,2)", "[2,6)", "[6,9)", "[9,12)") )
     xlevels <- levels(xfac)

     if(length(xlevels) != nlevels(factor(xdf$a.cut))) {
        v <- setdiff(xlevels, factor(xdf$a.cut))
        u <- data.frame(a = 0, a.cut = v)
        x <- rbind(u, x)
     }
return(x)
}

AddMissingLevel(x)

Does a more general approach exist, e.g. using "expand.grid"?

Thanks for any help!!
Patrick



More information about the R-help mailing list