在这篇文章中,我将概述最常用的包和博客,其中包含从不太直接的对象生成latex表的代码。请随意添加任何我错过的,和/或给提示,提示和小技巧,如何用R生成漂亮的乳胶表。

包:

xtable : for standard tables of most simple objects. A nice gallery with examples can be found here. memisc : tool for management of survey data, contains some tools for latex tables of (basic) regression model estimates. Hmisc contains a function latex() that creates a tex file containing the object of choice. It is pretty flexible, and can also output longtable latex tables. There's a lot of info in the help file ?latex miscFuncs has a neat function 'latextable' that converts matrix data with mixed alphabetic and numeric entries into a LaTeX table and prints them to the console, so they can be copied and pasted into a LaTeX document. texreg package (JSS paper) converts statistical model output into LaTeX tables. Merges multiple models. Can cope with about 50 different model types, including network models and multilevel models (lme and lme4). reporttools package (JSS paper) is another option for descriptive statistics on continuous, categorical and date variables. tables package is perhaps the most general LaTeX table making package in R for descriptive statistics stargazer package makes nice comparative statistical model summary tables

博客和代码片段

Paul Johnson的outreg函数在Latex中为回归的输出提供了类似stata的表。这个很好用。 正如在前面的问题中所给出的,有一个代码片段用于为lme4对象调整memisc包。

相关问题:

R/LaTeX表创建包的建议 Rreport/LaTeX质量输出包 使用xtable对latex输出的表进行排序 有办法从lme4 mer模型拟合对象产生一个LaTeX表吗? R data.frame与堆叠指定标题乳胶输出与xtable 从R自动向latex快速添加表,使用公式语言提供非常灵活和有趣的语法


当前回答

我有一些关于xtable和Latex有趣的“特性”的技巧和工作,我将在这里分享。

技巧#1:删除列中的重复项和技巧#2:使用书签

首先,加载包并定义clean函数

<<label=first, include=FALSE, echo=FALSE>>= 
    library(xtable)
    library(plyr)

    cleanf <- function(x){     
        oldx <- c(FALSE, x[-1]==x[-length(x)])  
        # is the value equal to the previous?    
        res <- x
        res[oldx] <- NA
        return(res)} 

现在生成一些假数据

data<-data.frame(animal=sample(c("elephant", "dog", "cat", "fish", "snake"), 100,replace=TRUE),
            colour=sample(c("red", "blue", "green", "yellow"), 100,replace=TRUE),
            size=rnorm(100,mean=500, sd=150),
            age=rlnorm(100, meanlog=3, sdlog=0.5))

    #generate a table
    datatable<-ddply(data, .(animal, colour), function(df) {
                return(data.frame(size=mean(df$size), age=mean(df$age)))
            })

现在我们可以生成一个表,并使用clean函数删除标签列中的重复项。

cleandata<-datatable
cleandata$animal<-cleanf(cleandata$animal)
cleandata$colour<-cleanf(cleandata$colour)
@ 

这是一个普通的xtable

<<label=normal, results=tex, echo=FALSE>>=
print(
    xtable(
        datatable
        ),
        tabular.environment='longtable',
        latex.environments=c("center"), 
        floating=FALSE, 
        include.rownames=FALSE
    )
@ 

这是一个普通的xtable,其中一个自定义函数已经将副本转换为NA

<<label=cleandata, results=tex, echo=FALSE>>=
print(
    xtable(
        cleandata
        ),
        tabular.environment='longtable',
        latex.environments=c("center"), 
        floating=FALSE, 
        include.rownames=FALSE
    )
@ 

这个表使用booktab包(并且在头文件中需要一个\usepackage{booktabs})

\begin{table}[!h] 
        \centering
        \caption{table using booktabs.}
        \label{tab:mytable}
<<label=booktabs, echo=F,results=tex>>= 
            mat <- xtable(cleandata,digits=rep(2,ncol(cleandata)+1))
            foo<-0:(length(mat$animal))
            bar<-foo[!is.na(mat$animal)]
            print(mat, 
                  sanitize.text.function = function(x){x},
                  floating=FALSE,
                  include.rownames=FALSE,
                  hline.after=NULL, 
                  add.to.row=list(pos=list(-1,bar,nrow(mat)), 
                  command=c("\\toprule ", "\\midrule ", "\\bottomrule ")))
  #could extend this with \cmidrule to have a partial line over
  #a sub category column and \addlinespace to add space before a total row
@ 

其他回答

我有一些关于xtable和Latex有趣的“特性”的技巧和工作,我将在这里分享。

技巧#1:删除列中的重复项和技巧#2:使用书签

首先,加载包并定义clean函数

<<label=first, include=FALSE, echo=FALSE>>= 
    library(xtable)
    library(plyr)

    cleanf <- function(x){     
        oldx <- c(FALSE, x[-1]==x[-length(x)])  
        # is the value equal to the previous?    
        res <- x
        res[oldx] <- NA
        return(res)} 

现在生成一些假数据

data<-data.frame(animal=sample(c("elephant", "dog", "cat", "fish", "snake"), 100,replace=TRUE),
            colour=sample(c("red", "blue", "green", "yellow"), 100,replace=TRUE),
            size=rnorm(100,mean=500, sd=150),
            age=rlnorm(100, meanlog=3, sdlog=0.5))

    #generate a table
    datatable<-ddply(data, .(animal, colour), function(df) {
                return(data.frame(size=mean(df$size), age=mean(df$age)))
            })

现在我们可以生成一个表,并使用clean函数删除标签列中的重复项。

cleandata<-datatable
cleandata$animal<-cleanf(cleandata$animal)
cleandata$colour<-cleanf(cleandata$colour)
@ 

这是一个普通的xtable

<<label=normal, results=tex, echo=FALSE>>=
print(
    xtable(
        datatable
        ),
        tabular.environment='longtable',
        latex.environments=c("center"), 
        floating=FALSE, 
        include.rownames=FALSE
    )
@ 

这是一个普通的xtable,其中一个自定义函数已经将副本转换为NA

<<label=cleandata, results=tex, echo=FALSE>>=
print(
    xtable(
        cleandata
        ),
        tabular.environment='longtable',
        latex.environments=c("center"), 
        floating=FALSE, 
        include.rownames=FALSE
    )
@ 

这个表使用booktab包(并且在头文件中需要一个\usepackage{booktabs})

\begin{table}[!h] 
        \centering
        \caption{table using booktabs.}
        \label{tab:mytable}
<<label=booktabs, echo=F,results=tex>>= 
            mat <- xtable(cleandata,digits=rep(2,ncol(cleandata)+1))
            foo<-0:(length(mat$animal))
            bar<-foo[!is.na(mat$animal)]
            print(mat, 
                  sanitize.text.function = function(x){x},
                  floating=FALSE,
                  include.rownames=FALSE,
                  hline.after=NULL, 
                  add.to.row=list(pos=list(-1,bar,nrow(mat)), 
                  command=c("\\toprule ", "\\midrule ", "\\bottomrule ")))
  #could extend this with \cmidrule to have a partial line over
  #a sub category column and \addlinespace to add space before a total row
@ 

你也可以使用R包micsFuncs中的latextable函数:

http://cran.r-project.org/web/packages/miscFuncs/index.html

latextable(M),其中M是一个混合字母和数字条目的矩阵,输出一个基本的LaTeX表到屏幕上,可以复制和粘贴到LaTeX文档中。如果有小数字,它也用索引符号替换这些数字(例如1.2x10^{-3})。

观星包是另一个不错的选择。它支持来自许多常用函数和包(lm、glm、svyreg、survival、pscl、AER)以及来自zelig的对象。除了回归表,它还可以输出数据帧的汇总统计,或者直接输出数据帧的内容。

另一个用于将多个回归模型聚合到LaTeX表中的R包是texreg。

... 和技巧#3在Xtable中多行条目

生成更多数据

moredata<-data.frame(Nominal=c(1:5), n=rep(5,5), 
        MeanLinBias=signif(rnorm(5, mean=0, sd=10), digits=4), 
        LinCI=paste("(",signif(rnorm(5,mean=-2, sd=5), digits=4),
                ", ", signif(rnorm(5, mean=2, sd=5), digits=4),")",sep=""),
        MeanQuadBias=signif(rnorm(5, mean=0, sd=10), digits=4), 
        QuadCI=paste("(",signif(rnorm(5,mean=-2, sd=5), digits=4),
                ", ", signif(rnorm(5, mean=2, sd=5), digits=4),")",sep=""))

names(moredata)<-c("Nominal", "n","Linear Model \nBias","Linear \nCI", "Quadratic Model \nBias", "Quadratic \nCI")

现在生成我们的xtable,使用sanze函数用正确的Latex换行命令替换列名(包括双反斜杠,这样R就满意了)

<<label=multilinetable, results=tex, echo=FALSE>>=
foo<-xtable(moredata)
align(foo) <- c( rep('c',3),'p{1.8in}','p{2in}','p{1.8in}','p{2in}' )
print(foo, 
            floating=FALSE, 
            include.rownames=FALSE,
            sanitize.text.function = function(str) {
                str<-gsub("\n","\\\\", str, fixed=TRUE)

                return(str)
            }, 
            sanitize.colnames.function = function(str) {
                str<-c("Nominal", "n","\\centering Linear Model\\\\ \\% Bias","\\centering Linear \\\\ 95\\%CI", "\\centering Quadratic Model\\\\ \\%Bias", "\\centering Quadratic \\\\ 95\\%CI \\tabularnewline")
                return(str)
            })
@  

(虽然这并不完美,因为我们需要\tabularnewline来正确格式化表格,Xtable仍然放入一个最终的\,所以我们最终在表头下面有一个空行。)