使用xtable打印data.table时控制输出

时间:2015-02-17 23:53:30

标签: r data.table knitr xtable

这是一个包含大量记录/行的data.table

dt <- data.table(a=sample(letters,1000,replace = T), b=rnorm(1000))

我们可以简单地查看它:

dt

...用第一行和最后5行生成一个非常方便的视图。

但是,当使用xtable使用knitr为pdf报告打印时,xtable会打印所有数千行:

print(xtable(dt))

任何想法如何解决这个问题?

我想要一个来自xtable的漂亮表格,但默认格式为data.table

rbind那样有第一个和最后五个元素的黑客是可能的,但不是很优雅。

1 个答案:

答案 0 :(得分:1)

以下是print.data.table的修改版本,它返回格式化对象而不是打印它:

firstLast <- function(x, ...) {
    UseMethod("firstLast")
}

firstLast.data.table  <- function (x,
                                   topn = getOption("datatable.print.topn"),
                                   nrows = getOption("datatable.print.nrows"),
                                   row.names = TRUE, ...) {
    if (!is.numeric(nrows)) 
        nrows = 100L
    if (!is.infinite(nrows)) 
        nrows = as.integer(nrows)
    if (nrows <= 0L) 
        return(invisible())
    if (!is.numeric(topn)) 
        topn = 5L
    topnmiss = missing(topn)
    topn = max(as.integer(topn), 1L)
    if (nrow(x) == 0L) {
        if (length(x) == 0L) 
            return("Null data.table (0 rows and 0 cols)\n")
        else return(paste("Empty data.table (0 rows) of ", length(x), 
            " col", if (length(x) > 1L) 
                "s", ": ", paste(head(names(x), 6), collapse = ","), 
            if (ncol(x) > 6) 
                "...", "\n", sep = ""))
    }
    if (topn * 2 < nrow(x) && (nrow(x) > nrows || !topnmiss)) {
        toprint = rbind(head(x, topn), tail(x, topn))
        rn = c(seq_len(topn), seq.int(to = nrow(x), length.out = topn))
        printdots = TRUE
    }
    else {
        toprint = x
        rn = seq_len(nrow(x))
        printdots = FALSE
    }
    toprint = data.table:::format.data.table(toprint, ...)
    if (isTRUE(row.names)) 
        rownames(toprint) = paste(format(rn, right = TRUE), ":", 
            sep = "")
    else rownames(toprint) = rep.int("", nrow(x))
    if (is.null(names(x))) 
        colnames(toprint) = rep("NA", ncol(toprint))
    if (printdots) {
        toprint = rbind(head(toprint, topn), `---` = "", tail(toprint, 
            topn))
        rownames(toprint) = format(rownames(toprint), justify = "right")
        return(toprint)
    }
    if (nrow(toprint) > 20L) 
        toprint = rbind(toprint, matrix(colnames(toprint), nrow = 1))
    return(toprint)
}

这可以用来为xtable格式化大型data.table格式:

library(xtable)
xtable(firstLast(dt))
% latex table generated in R 3.1.2 by xtable 1.7-4 package
% Tue Feb 17 20:15:12 2015
\begin{table}[ht]
\centering
\begin{tabular}{rll}
  \hline
 & a & b \\ 
  \hline
   1: & i & -0.6356429 \\ 
     2: & w & -1.1533783 \\ 
     3: & r & -0.7459959 \\ 
     4: & x &  1.5646809 \\ 
     5: & o & -1.8158744 \\ 
    --- &  &  \\ 
   996: & z & -1.0835897 \\ 
   997: & a &  0.9219506 \\ 
   998: & q &  0.3388118 \\ 
   999: & l & -1.7123250 \\ 
  1000: & l &  0.1240633 \\ 
   \hline
\end{tabular}
\end{table}