rr-markdown

RMarkDown doesn't work with loops and color designs


I created some tables in document "RExample.r" and they look fine. When I pass them to RmarkDown I have 3 results:

  1. Example_With_Out_Bucle_1: works fine.
  2. Example_With_Out_Bucle_2: doesn't even show in the html.
  3. Example_With_Bucle: Shows only code.

How can I make example 3 work?

I created some sample tables, for me its important to execute the RmarkDown directly from the R document.

# example_script.R

# Create a list of example tables for different divisions
Lista_Tablas_10Semanas_Por_Division <- list()

# Create mock tables for 3 divisions with Weeks as columns and Sales, Orders, Items as rows
Lista_Tablas_10Semanas_Por_Division[["Division_A"]] <- data.frame(
  Metric = c("Sales", "Orders", "Items"),
  W202401 = c(4000, 150, 250),
  W202402 = c(4500, 200, 300),
  W202403 = c(3000, 120, 180),
  W202404 = c(5000, 250, 350),
  W202405 = c(3500, 180, 220)
)

Lista_Tablas_10Semanas_Por_Division[["Division_B"]] <- data.frame(
  Metric = c("Sales", "Orders", "Items"),
  W202401 = c(4200, 130, 240),
  W202402 = c(4700, 170, 290),
  W202403 = c(3300, 100, 190),
  W202404 = c(5200, 260, 340),
  W202405 = c(3700, 190, 210)
)

Lista_Tablas_10Semanas_Por_Division[["Division_C"]] <- data.frame(
  Metric = c("Sales", "Orders", "Items"),
  W202401 = c(3800, 160, 230),
  W202402 = c(4400, 180, 290),
  W202403 = c(3100, 140, 170),
  W202404 = c(5100, 230, 340),
  W202405 = c(3600, 200, 250)
)

# Check if the list is created properly
print(names(Lista_Tablas_10Semanas_Por_Division))

library(rmarkdown)
getwd()
setwd("C:\\Users\\fvarelaa\\Desktop")
getwd()
archivo_rmd <- "C:\\Users\\fvarelaa\\Desktop\\RMarkDownExample.Rmd"
# Ejecutar el archivo RMarkdown y generar el reporte en HTML
render(archivo_rmd, output_format = "html_document", output_file = "Example.html")

The results of the tables are as in this image:

Result in Console

This is my code in RmarkDown:

---
title: "Example Report"
author: "Your Name"
date: "`r Sys.Date()`"
output: 
  html_document:
    df_print: paged
---

#```{r setup1, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, message = FALSE, warning = FALSE)
library(kableExtra)
library(plotly)
library(ggplot2)
library(scales)

# Variables de colores
purple_color <- "#4B0082"
white_color <- "#FFFFFF"
#```


#```{r Example_With_Out_Bucle_1}  
  kable(Lista_Tablas_10Semanas_Por_Division$Division_A) %>%
  kable_styling(bootstrap_options = c("striped", "hover", "condensed"))
#```


#```{r Example_With_Out_Bucle_2}

# Display the title for Division A
#cat("### Division: Division_A\n\n")

# Get the table for Division_A
table <- Lista_Tablas_10Semanas_Por_Division$Division_A

# Check if the table exists and print it using kable
if (!is.null(table)) {
  print(
    kable(table, format = "html", table.attr = "style='width:80%;'") %>%
    kable_styling(bootstrap_options = c("striped", "hover", "condensed", "responsive")) %>%
    row_spec(0, bold = TRUE, color = "white", background = "#4B0082")
  )
} else {
  cat("No data available for this table.\n")
}

#```


#```{r example_With_Bucle}  
# Loop through each Division in Lista_Tablas_10Semanas_Por_Division
for (division in names(Lista_Tablas_10Semanas_Por_Division)) {
  
  # Display the division title
  cat("### Division: ", gsub("_", " ", division), "\n\n")
  
  # Extract the table for the current division
  tabla_10semanas <- Lista_Tablas_10Semanas_Por_Division[[division]]
  
  # Render the table using kable and kableExtra
  print(
    kable(tabla_10semanas, format = "html", table.attr = "style='width:80%;'") %>%
      kable_styling(bootstrap_options = c("striped", "hover", "condensed", "responsive")) %>%
      row_spec(0, bold = TRUE, color = "white", background = "#4B0082")
  )
  
  cat("\n\n")  # Space between divisions
}
#```

And this are my results:

Image of the HTML Result

As you can see, only the chunk without loop and without design are working. Another interesting fact is that in Viewer the tables show with the proper design:

Tables with design in viewer


Solution

  • To write chunk output as-is, set results='asis' option.

    Another issue raises when print() method of kableExtra gets called in an interactive RStudio session (it turns objects into shiny.class.list for RStudio inline preview & Viewer). This is something we generally do not have to worry about as knitting takes place in a separate session, but here you are likely calling rmarkdown::render() from interactive RStudio session.

    In previous revision I suggested using cat() instead of print() to handle this, though kableExtra print behaviour can also be controlled with kableExtra_view_html option. When toggling this through Rmd parameters, view html can be disabled when rendering with rmarkdown::render(..., params = list(kableExtra_view_html = FALSE)) while keeping proper rendered table previews in RStudio when working with the document interactively.

    tmp.Rmd:

    ---
    output: html_document
    params:
      kableExtra_view_html: TRUE
    ---
    
    ```{r setup, include=FALSE}
    knitr::opts_chunk$set(echo = FALSE)
    
    library(kableExtra)
    library(magrittr)
    
    # disable kableExtra preview in RStudio viewer so we could use 
    # kableExtra print() method in asis chunks while rendering from  interactive session:
    # options(kableExtra_view_html = FALSE)
    
    # or control kableExtra_view_html option through params:
    options(kableExtra_view_html = params$kableExtra_view_html)
    ```
    
    ```{r example_With_Bucle, results='asis'}  
    for (division in names(Lista_Tablas_10Semanas_Por_Division)) {
      
      # Display the division title
      cat("### Division: ", gsub("_", " ", division), "\n\n")
      
      # Extract the table for the current division
      tabla_10semanas <- Lista_Tablas_10Semanas_Por_Division[[division]]
      
      # Render the table using kable and kableExtra
      kable(tabla_10semanas, row.names = FALSE, format = "html", table.attr = "style='width:80%;'") %>%
        kable_styling(bootstrap_options = c("striped", "hover", "condensed", "responsive")) %>%
        row_spec(0, bold = TRUE, color = "white", background = "#4B0082") %>%
        print() 
    }
    ```
    

    Prepare MRE and render with disabled kableExtra_view_html:

    # list of frames for minimal reproducible example
    Lista_Tablas_10Semanas_Por_Division <- split(iris, ~Species) |> lapply(head, n = 3)
    rmarkdown::render("tmp.Rmd", params = list(kableExtra_view_html = FALSE))
    
    

    Rendered result: Rendered rmd