Creating a Custom ftable Function in R: A Step-by-Step Guide

Here is the final answer to the problem:

replace_empty_arguments <- function(a) {
  empty_symbols <- vapply(a, function(x) {
    is.symbol(x) &amp;&amp; identical("", as.character(x)), 0)
  }
  a[!!empty_symbols] <- 0
  lapply(a, eval)
}

`.ftable` <- function(inftable, ...) {
  if (!class(inftable) %in% "ftable") stop("input is not an ftable")
  tblatr <- attributes(inftable)[c("row.vars", "col.vars")]
  valslist <- replace_empty_arguments(as.list(match.call()[-(1:2)]))
  x <- sapply(valslist, function(x) identical(x, 0))
  TAB <- as.table(inftable)
  valslist[x] <- dimnames(TAB)[x]
  temp <- expand.grid(valslist)
  out <- ftable(`dimnames<-`(TAB[temp], lengths(valslist)), row.vars = seq_along(tblatr[["row.vars"]]), col.vars = seq_along(tblatr[["col.vars"]]) + length(tblatr[["row.vars"]]))
  names(attributes(out)[["row.vars"]]) <- names(tblatr[["row.vars"]])
  names(attributes(out)[["col.vars"]]) <- names(tblatr[["col.vars"]])
  out
}

Last modified on 2023-05-04