Hello, Currently it's possible to convert an object of class table to a data frame with as.data.frame.table(), but there's no ready-made function, AFAIK, to do the reverse operation, i.e. conversion of a data frame to a table.
Do you think it would be a good idea to add a data.frame method to as.table(), to allow such conversions? The idea is that if `x' is a table and `y <- as.data.frame(x)', then the object returned by `as.table(y)' should be equal to `x'. Below is a proof of concept as.table.data.frame <- function(x, ..., response) { if (missing(response)) resp <- ncol(x) else { resp <- match(response[1L], names(x)) if (is.na(resp)) stop('not found: ', response[1L]) } x[-resp] <- lapply(x[-resp], as.factor) if (any(do.call(table, x[-resp]) > 1L)) stop('repeated frequency value') dn <- lapply(x[-resp], function(y) { if (any(is.na(y))) c(levels(y), NA) else levels(y) }) ind <- mapply(function(val, lev) match(val, lev), x[-resp], dn) out <- array(dim=unlist(lapply(dn, length)), dimnames=dn) out[ind] <- x[[resp]] as.table(out) } and a simple usage example: > (y <- table(foo=c('a','a',NA,'b','b'), useNA='always')) foo a b <NA> 2 2 1 > (yy <- as.data.frame(y)) foo Freq 1 a 2 2 b 2 3 <NA> 1 > as.table(yy) foo a b <NA> 2 2 1 > Any thoughts? ______________________________________________ R-devel@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-devel