2010-10-07 110 views
32

有没有一种方法可以像生成一个图(即用pdf()或ggsave())一样从R生成一个表的PDF?我知道有其他程序(使用sweave等)的方法,但我想从R生成它。创建一个PDF表格

回答

30

是的,因为您可以将文本放入图形中,因此放入pdf设备。

最好的包装可能是Greg Warnes'值得信赖的gplots包中的textplot()函数。下面是它的帮助页的示例部分的开头:

# show R version information 
textplot(version) 
# show the alphabet as a single string 
textplot(paste(letters[1:26], collapse=" ")) 

# show the alphabet as a matrix 
textplot(matrix(letters[1:26], ncol=2)) 

### Make a nice 4 way display with two plots and two text summaries 
data(iris) 
par(mfrow=c(2,2)) 
plot(Sepal.Length ~ Species, data=iris, border="blue", col="cyan", 
     main="Boxplot of Sepal Length by Species")  
plotmeans(Sepal.Length ~ Species, data=iris, barwidth=2, connect=FALSE, 
      main="Means and 95\% Confidence Intervals\nof Sepal Length by Species") 

info <- sapply(split(iris$Sepal.Length, iris$Species), 
       function(x) round(c(Mean=mean(x), SD=sd(x), N=gdata::nobs(x)),2)) 

textplot(info, valign="top" ) 
title("Sepal Length by Species") 

reg <- lm(Sepal.Length ~ Species, data=iris) 
textplot(capture.output(summary(reg)), valign="top") 
title("Regression of Sepal Length by Species") 

par(mfrow=c(1,1)) 
+0

谢谢,这似乎是工作! – Tom 2010-10-07 13:34:03

4

还有在plotrix包addtable2plot功能。

14

另请参阅grid.tablegridExtra,使用网格图形。

4

我最近想这样做,但不喜欢grideExtratextplot的输出格式,所以我写了这个函数来做胶乳。这是一个黑客位工作,并有与sweaveknitr更好的方法,但你可能会发现它很有用修改你的目的:

createPDF <- function(xx, name=deparse(substitute(xx))){ 
    require(xtable) 
    tt <- print(xtable(xx), type='latex') 
    texfile <- paste0('./reports/', name, '.tex') 
    cat(
    '\\documentclass[12pt]{report} 
\\usepackage[landscape]{geometry} 
\\date{} 
\\begin{document}', tt, '\\end{document}', sep='', 
    file=texfile 
) 
    ## pdflatex from texlive package for linux converts .tex to .pdf 
    system(paste0('pdflatex ', '-output-directory ./reports ', texfile)) 
}