Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

writing data frame to pdf table

Tags:

r

I have a data frame which I would like to write it to a pdf file in organized fashion.

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 to be group by Date, place a space or line break after each group;

I have this piece of code but this prints out everything to the pdf file without grouping:

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

Any ideas how can best present this data set in a pdf file with grouping on Date? I like to use grid.Extra. Anybody knows how to put a title to grid.Extra?

like image 858
user1471980 Avatar asked Jan 14 '13 15:01

user1471980


3 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

like image 157
Andrey Dyachenko Avatar answered Sep 29 '22 09:09

Andrey Dyachenko


I really recommend you to use Rstudio with Knitr. It is very easy to create good reports.

For example,

\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

like image 28
agstudy Avatar answered Sep 29 '22 11:09

agstudy


As of 2017, there is good support in R-studio presentation formats (Markdown) with package "pander", and output to PDF via Beamer. See pander : http://rapporter.github.io/pander/#pander-an-r-pandoc-writer

Example in R-studio presentation code to print a data frame as table :

```{r}    
pander(df)
```
like image 36
Dan Gustafsson Avatar answered Sep 29 '22 10:09

Dan Gustafsson