Skip to content
Prev 167636 / 398502 Next

generalizing expand.table: table -> data.frame

on 01/20/2009 10:38 AM Michael Friendly wrote:
Hi Michael,

I think that the following modifications to my original code, also
incorporating the changes made in the NCstats package should work.


expand.dft <- function(x, var.names = NULL, freq = "Freq", ...)
{
  #  allow: a table object, or a data frame in frequency form
  if(inherits(x, "table"))
    x <- as.data.frame.table(x, responseName = freq)

  freq.col <- which(colnames(x) == freq)
  if (length(freq.col) == 0)
      stop(paste(sQuote("freq"), "not found in column names"))

  DF <- sapply(1:nrow(x),
               function(i) x[rep(i, each = x[i, freq.col]), ],
               simplify = FALSE)

  DF <- do.call("rbind", DF)[, -freq.col]

  for (i in 1:ncol(DF))
  {
    DF[[i]] <- type.convert(as.character(DF[[i]]), ...)

  }

  rownames(DF) <- NULL

  if (!is.null(var.names))
  {
    if (length(var.names) < dim(DF)[2])
    {
      stop(paste("Too few", sQuote("var.names"), "given."))
    } else if (length(var.names) > dim(DF)[2]) {
      stop(paste("Too many", sQuote("var.names"), "given."))
    } else {
      names(DF) <- var.names
    }
  }

  DF
}
Improved
Treatment None Some Marked
  Placebo   29    7      7
  Treated   13    7     21
Treatment Improved
1    Placebo     None
2    Placebo     None
3    Placebo     None
4    Placebo     None
5    Placebo     None
6    Placebo     None
7    Placebo     None
8    Placebo     None
9    Placebo     None
10   Placebo     None



art.dft <- as.data.frame.table(art)
Treatment Improved Freq
1   Placebo     None   29
2   Treated     None   13
3   Placebo     Some    7
4   Treated     Some    7
5   Placebo   Marked    7
6   Treated   Marked   21

names(art.dft)[3] <- "count"
Treatment Improved count
1   Placebo     None    29
2   Treated     None    13
3   Placebo     Some     7
4   Treated     Some     7
5   Placebo   Marked     7
6   Treated   Marked    21
Treatment Improved
1    Placebo     None
2    Placebo     None
3    Placebo     None
4    Placebo     None
5    Placebo     None
6    Placebo     None
7    Placebo     None
8    Placebo     None
9    Placebo     None
10   Placebo     None


HTH,

Marc Schwartz