Create a PDF table

后端 未结 5 1109
庸人自扰
庸人自扰 2020-11-29 20:40

Is there a way to produce a PDF of a table from R in the same way you produce a plot (ie with pdf() or ggsave())? I realize there are ways with other programs (using sweave

相关标签:
5条回答
  • 2020-11-29 20:54

    Yes there is as you can place text into graphs and hence into pdf devices.

    The nicest wrapper for this may be the textplot() function in Greg Warnes' trusted gplots package. Below is the beginning of the examples section of its help page:

    # 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 讨论(0)
  • 2020-11-29 21:00

    There is also the addtable2plot function in the plotrix package.

    0 讨论(0)
  • 2020-11-29 21:02

    see also grid.table in gridExtra, using grid graphics.

    0 讨论(0)
  • 2020-11-29 21:18

    Here's a one-liner using my library:

    library(huxtable)
    my_table <- table(mtcars$gear, mtcars$cyl)
    quick_pdf(my_table) # produces a PDF in the current directory
    
    0 讨论(0)
  • 2020-11-29 21:21

    I recently wanted to do this but didn't like the output format of grideExtra or textplot so I wrote this function to do it in latex. It's a bit of a hack job and there are better ways with sweave or knitr, but you might find it useful to modify for your purposes:

    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))
    }
    
    0 讨论(0)
提交回复
热议问题