[Rd] Code Optimization: print.data.frame + as.data.frame(head(x, n = options("max.print")))

Juan Telleria Ruiz de Aguirre
Mon, 30 Jul 2018 19:27:57 -0000

Dear R Developers,

I would like to propose a simple optimization for print.data.frame
base function:

To add: x <- as.data.frame(head(x, n = options("max.print")))

This would prevent that, if for example, we have a 10GB data.frame
(e.g.: Instead of a data.table), and we accidentally print it, the R
Session does not "collapse", forcing us to press ESC or kill the
RSession.

function (x, ..., digits = NULL, quote = FALSE, right = TRUE,
          row.names = TRUE)
{
  n <- length(row.names(x))
  if (length(x) == 0L) {
    cat(sprintf(ngettext(n, "data frame with 0 columns and %d row",
                         "data frame with 0 columns and %d rows"), n),
"\n",
        sep = "")
  }
  else if (n == 0L) {
    print.default(names(x), quote = FALSE)
    cat(gettext("<0 rows> (or 0-length row.names)\n"))
  }
  else {

    x <- as.data.frame(head(x, n = options("max.print")))

    m <- as.matrix(format.data.frame(x, digits = digits,
                                     na.encode = FALSE))
    if (!isTRUE(row.names))
      dimnames(m)[[1L]] <- if (isFALSE(row.names))
        rep.int("", n)
    else row.names
    print(m, ..., quote = quote, right = right)
  }
  invisible(x)
}

Thank you.

Best,
Juan