[R] Expand DF with all levels of a variable
Dimitris Rizopoulos
d.rizopoulos at erasmusmc.nl
Tue Jun 14 13:42:54 CEST 2011
here is a solution with expand.grid(),
a <- c(2,2,3,4,5,6,7,8,9)
a.cut <- cut(a, breaks=c(0,2,6,9,12,13,15,16), right=FALSE )
x <- data.frame(a, a.cut)
out <- expand.grid(a = 0, a.cut = setdiff(levels(a.cut), unique(a.cut)))
rbind(out, x)
I hope it helps.
Best,
Dimitris
On 6/14/2011 1:32 PM, Patrick Hausmann wrote:
> 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 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.
>
--
Dimitris Rizopoulos
Assistant Professor
Department of Biostatistics
Erasmus University Medical Center
Address: PO Box 2040, 3000 CA Rotterdam, the Netherlands
Tel: +31/(0)10/7043478
Fax: +31/(0)10/7043014
Web: http://www.erasmusmc.nl/biostatistiek/
More information about the R-help
mailing list