Writing data frame to pdf table

I have a data frame that I would like to write to a pdf file in an organized manner.

For example, my df looks like this:

Date County Trade 1/1/2012 USA 5 1/1/2012 Japan 4 1/2/2012 USA 10 1/3/2012 Germany 15 

I would like to output the group by date, put a space or line break after each group;

I have this piece of code, but it prints everything in a pdf file without grouping:

 library(gridExtra) pdf("trade.pdf", height=11, width=8.5) grid.table(df) dev.off() 

Any ideas how best to present this dataset in a pdf file grouped by date? I like to use grid.Extra. Does anyone know how to put a header in grid.Extra?

+4
source share
4 answers

This code should work:

 library(gridExtra) df <- read.table(text = "1/1/2012 USA 5 1/1/2012 Japan 4 1/2/2012 USA 10 1/3/2012 Germany 15" ) names(df) <- c("Date","Country","Trade") EqDatedf <- as.data.frame(df[1,]) EmptyLine <- data.frame(Date = "",Country = "",Trade = "") pdf(file = "q.pdf") for (i in 2:nrow(df)) { if (as.vector(df$Date[i]) == as.vector(df$Date[i-1])) {EqDatedf <- rbind(EqDatedf, df[i,])} else { EqDatedf <- rbind(EqDatedf, EmptyLine) EqDatedf <- rbind(EqDatedf, df[i,]) } } grid.table(EqDatedf, show.rownames = FALSE) dev.off() 

enter image description here

+10
source

I really recommend you use Rstudio with Knitr . Creating good reports is easy.

For instance,

 \documentclass{article} \begin{document} <<myTable,results='asis'>>= library(xtable) tab <- read.table(text = 'Date County Trade 1/1/2012 USA 5 1/1/2012 Japan 4 1/2/2012 USA 10 1/3/2012 Germany 15',header = TRUE) print(xtable(tab),hline.after=c(2,3)) ## print.xtable have many smart options @ \end{document} 

enter image description here

+8
source

The grid.table solution will be the fastest way to create PDFs for short tables, but this solution will not work as if you had a table that was longer than 1 page. RStudio + knitr + longtable is probably the way to create well-formatted PDF files. You will need something like:

 \documentclass{article} \usepackage{longtable} \begin{document} <<results='asis'>>= library(xtable) df = data.frame(matrix(rnorm(400), nrow=100)) xt = xtable(df) print(xt, tabular.environment = "longtable", floating = FALSE ) @ \end{document} 

Pls see this one for more details.

+1
source

As of 2017, R-studio (Markdown) presentation formats have good support with the "pander" package and PDF output via Beamer. See Pander: http://rapporter.imtqy.com/pander/#pander-an-r-pandoc-writer

An example in the R-studio presentation code for printing a data frame in the form of a table:

 ```{r} pander(df) ``` 
+1
source

All Articles