Table Rendering in Pdf Document Using R Markdown

Table Rendering in Pdf Document Using R Markdown

After days trying to find a solution, I give up and ask for help.

I decided to use R Markdown very recently. While I can render plots as I want, I cannot succeed in rendering my tables in a pdf doc properly.

Here the corresponding [EDITED]code:

---
title: "My_title"
output:
  pdf_document: default
  html_document:
    df_print: paged
params:
  date: "!r Sys.Date()"
---

{r library, echo=F, message=F, warning=F, paged.print=FALSE}
suppressMessages(library("knitr"))
suppressMessages(library(reshape2))
suppressMessages(library(splines))
suppressMessages(library(kableExtra))
suppressMessages(library(gplots))


{r, setup, echo = F}
opts_knit$set(root.dir = "my_path")
knitr::opts_chunk$set(echo = F)



{r}
dt <- expand.grid(Region=c("a","b","c"), Country=c("d","e","f"), Cancer= c("All", "CRC", "Breast"), 
             age.1.1=1:2,
             age.1.2=1:2,
             age.1.3=1:2)



   {r Table_1, INCLUDE = TRUE}

  cancer.lab <- c("All", "CRC", "Breast")

  for (i in 1:3){

   b <- dt[dt$Cancer==cancer.lab[i],]

   b <- b[,-3]

   t <- kable(b, format = ,caption = "Fig", row.names = F) %>%
   kable_paper() %>%
   kable_styling(font_size = 9) %>%
   add_header_above(c(" " = 2, "1998" = 3))

   print(t)
  }
  

Again I am new and I surely miss something.

I use Mac if it may explain something.

Thank you for your help.

Sophie.

9

1 Answer

I think this is the same issue as dealt with here: . The problem is that you need to use knit_print to print the tables, but you can't do that in a loop.

So if you change the last code chunk to this, it should work:

   {r Table_1, INCLUDE = TRUE}
  results <- c()

  cancer.lab <- c("All", "CRC", "Breast")

  for (i in 1:3){

   b <- dt[dt$Cancer==cancer.lab[i],]

   b <- b[,-3]

   t <- kable(b, format = ,caption = "Fig", row.names = F) %>%
   kable_paper() %>%
   kable_styling(font_size = 9) %>%
   add_header_above(c(" " = 2, "1998" = 3))

   results <- c(results, knit_print(t))
  }
  asis_output(results)
  
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sarah Jenkins
Author

Sarah Jenkins

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.