How to draw two & ldquo; formattable & rdquo; the class data tables in the same chart and export to PDF in R?

advertisements

new stackoverflow user here, so apologies if this question/context is not up to standard. I welcome feedback.

I have two data frames that I would like to visualize as two separate tables in a PDF report. One of the data frames is a summary table that averages all the more granular level data from the second data frame. I am looking to put the summary table on top of the more granular level table. They are different sizes (different number of rows and columns), so let me know if that is a problem.

As for actual code/process, I am using the "formattable" package to make good looking tables; however I have no idea how to move on from there. I have tried using the grid.arrange function (from gridExtra package) and layout functions - but I get an error for grid.arrange and have not been able to figure out how to use the layout function (even after spending time reviewing other stackoverflow questions). Code is below:

library(formattable)
library(gridExtra)

m1 <- matrix("summary",1,3)
m2 <- matrix("granular",20,5)

t1 <- formattable(data.frame(m1))
t2 <- formattable(data.frame(m2))

layout(t1, t2, nrow=2)
grid.arrange(t1,t2, nrow=2, ncol=1)

for layout function I get the following error:

Error in layout(t1, t2, nrow = 2) : unused argument (nrow = 2)

and for grid.arrange i am getting the error:

Error in `$<-.data.frame`(`*tmp*`, "wrapvp", value = list(x = 0.5, y = 0.5,  :
  replacement has 17 rows, data has 1

Finally, as for the exporting to PDF part, I have not been able to even export ONE of the formattable class data frames, so I have no idea how I would export the both of them to a PDF. It appears in my working directory and also appears on the Plots window in RStudio, but it says: "There was an error opening this document. This file is already open or in use by another application." So I figure the file didn't process correctly. Using:

pdf("SamplePDF.pdf", width=11, height=8)
formattable(data.frame(m1))
dev.off()

I am doing this in R because I am taking advantage of the features of the "formattable" package and mean to eventually use the "RDCOMClient" to send these reports out automatically by email. Plus, SQL and R are basically the only "code" I know.

Thank you, and apologies in advance for a first-time poster!


Something like this works for me:

pdf('test00.pdf')
grid.table(t1)
grid.newpage()
grid.table(t2)
dev.off()

Although this forces different tables to be on different pages.