writing data frame to pdf table

后端 未结 4 1934
青春惊慌失措
青春惊慌失措 2020-12-05 12:46

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         


        
相关标签:
4条回答
  • 2020-12-05 12:51

    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

    0 讨论(0)
  • 2020-12-05 12:53

    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

    0 讨论(0)
  • 2020-12-05 12:55

    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)
    ```
    
    0 讨论(0)
  • 2020-12-05 13:09

    The grid.table solution will be the quickest way to create a PDF for short tables, but this solution will not work as is if you have a table that's longer than 1 page. RStudio + knitr + longtable is probably the way to go to create nicely formatted PDFs. What you'll need is 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 post for more details.

    0 讨论(0)
提交回复
热议问题