renozao / FAQR

Frequently Asked Questions on R: my personal Ask Just Once system for my friends' R problems...
0 stars 0 forks source link

Possible to export long table to multiple pages? #10

Open ArielW1 opened 9 years ago

ArielW1 commented 9 years ago

My problem - the table has more rows that can fit to one page, and R simply cropps all the rows that doesn't fit the first page.

My table("sorted_uni_table") looks like this:

image

And my output function is textplot() from gplots library:

textplot(sorted_uni_table,valign="top",halign="center",cex=1)

10x! Ariel

Rachelly commented 9 years ago

Why not export the table to a CSV/ TXT/ Excel file? You can use write.table() and then you don't have any problem with the table dimensions..

ArielW1 commented 9 years ago

That sounds plausible, but in this case the above is only one plot out of many, which are the output of a function, so I prefer to export it to pdf... Any ideas?

renozao commented 9 years ago

Not sure this is possible with textplot as it creates a plot, that is a single element. Try using this function, but you will be limited in term of number of columns (~ 13):

table2pdf <- function(x, file, fontsize = 11){ 

  if( fontsize < 4 ) stop("Fontsize must be >= 4")
  tfontsize <- if( fontsize < 8 ) paste0("\\\\", c('small', 'footnotesize', 'scriptsize', 'tiny')[8-fontsize]) else ''
  fontsize <- max(fontsize, 8)
  library(rmarkdown)
  dir.create(tmpd <- tempfile())
  file <- file.path(normalizePath(dirname(file)), basename(file))
  on.exit( unlink(tmpd, recursive = TRUE) )
  if( is.null(colnames(x)) ) colnames(x) <- seq(ncol(x))
  saveRDS(x, file.path(tmpd, 'x.rds'))
  write(sprintf("
---
output: pdf_document
fontsize: %spt
---
```{r, echo = FALSE, results = 'asis'}
x <- readRDS('x.rds')
cat('%s\\n')
knitr::kable(x)
```", fontsize, tfontsize), rmd <- file.path(tmpd, 'table.Rmd'))
  render(rmd, output_file = file, quiet = TRUE)
}

Usage:

x <- matrix(runif(1000), 250, 4)
table2pdf(x, 'test.pdf')
ArielW1 commented 9 years ago

Thanks, mate! :)

I only saw your code after finding an alternative solution: I decided in advance how many rows to put in each page, and I then splitted my table rows across different plots by a loop that enteres a different value (using recordPlot()) at each iteration.. (-: