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

______________________________________________
R-help@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.

Reply via email to