I am trying to render a static DT to word.
I have this stripped down version of a file example.Rmd and I am using knitr version 1.30 and the latest stable versions of all relevant packages. Per https://bookdown.org/yihui/bookdown/html-widgets.html the datatable should render but I am not getting the static DT back just the echo=TRUE part.
Please help me if you can - I am hopelessly stuck and I cannot just use another table.
title: 'Main title'
subtitle: 'Subtitle here'
always_allow_html: yes
# params:these will come from SHINY APP
# x1: x1
# x2: x2
# x3 :x3
output:
word_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
knitr::opts_chunk$set(out.width = '100%', dpi=300)
```
```{r, fig.align='center', echo=TRUE, cache=FALSE, warning = TRUE, message = TRUE, tidy=TRUE}
library(DT)
library(webshot)
if(is.null(webshot:::find_phantom())){webshot::install_phantomjs()}
DT::renderDataTable(iris)
```
The solution to this problem is to replace renderDataTable with datatable which allows webshot to kick in.
title: 'Main title'
subtitle: 'Subtitle here'
always_allow_html: yes
# params:these will come from SHINY APP
# x1: x1
# x2: x2
# x3 :x3
output:
word_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
knitr::opts_chunk$set(out.width = '100%', dpi=300)
```
```{r, fig.align='center', echo=TRUE, cache=FALSE, warning = TRUE, message = TRUE, tidy=TRUE}
library(DT)
library(webshot)
if(is.null(webshot:::find_phantom())){webshot::install_phantomjs()}
DT::datatable(iris)
```
Here is what I did, I am not sure if you can render DT into a static table file straight into Word like you are wanting, but maybe I am unaware. The DT is a javascript library so it's suppose to be dynamic and user interactive in a web browser. but the knitr::kable() function will render your table entirely straight into word.
---
title: 'Main title'
subtitle: 'Subtitle here'
always_allow_html: yes
runtime: shiny
output:
html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
knitr::opts_chunk$set(out.width = '100%', dpi=300)
```
```{r, fig.align='center', cache=FALSE, warning = FALSE, message = FALSE}
library(DT)
library(webshot)
if(is.null(webshot:::find_phantom())){webshot::install_phantomjs()}
DT::renderDataTable(iris)
```
Maybe use just a simple table output with knitr::kable, which will render your entire table straight to a word doc from Rmarkdown.
---
title: 'Main title'
subtitle: 'Subtitle here'
output:
word_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
knitr::opts_chunk$set(out.width = '100%', dpi=300)
```
```{r, fig.align='center', cache=FALSE, warning = FALSE, message = FALSE}
library(DT)
library(knitr)
knitr::kable(iris)
```
Related
Since yesterday, I get a confusing error, when trying to knit my Markdown files to PDF. I get this warning:
This is pdfTeX, Version 3.141592653-2.6-1.40.24 (TeX Live 2022) (preloaded format=pdflatex)
restricted \write18 enabled.
entering extended mode
I was unable to find any missing LaTeX packages from the error log Chapter-5-1.log.
! Extra }, or forgotten \endgroup.
\endwraptable ...kip \egroup \box \z# \fi \egroup
\WF#floatstyhook \def \wid...
l.156 \end{wraptable}
Fehler: LaTeX failed to compile Chapter-5-1.tex. See https://yihui.org/tinytex/r/#debugging for debugging tips. See Chapter-5-1.log for more info.
Ausführung angehalten
The problem seems to be the kable tables, which have been knit in prior tries just nicely. In the error log, this is printed:
Overfull \hbox (165.80571pt too wide) in paragraph at lines 142--158
[][]
[]
! Extra }, or forgotten \endgroup.
\endwraptable ...kip \egroup \box \z# \fi \egroup
\WF#floatstyhook \def \wid...
l.158 \end{wraptable}
A friend of mine tried to compile the tex file directly to PDF, but got the same error. We where not able to find a missing } or any other error in the coding. All tables and code is running without error in the markdown preview.
I get the same error, when I try to knit a document with a dummy table, so I hope that works as a reproducible example.
---
title: "Chapter 5"
author: "Moiken Hinrichs"
date: "`r format(Sys.time(), '%d.%m.%Y')`"
header-includes:
- \usepackage{caption}
- \usepackage{float}
- \captionsetup[figure]{font=footnotesize}
- \usepackage{subfig}
- \usepackage{flafter}
- \usepackage{footmisc}
output:
bookdown::pdf_document2:
extra_dependencies: ["flafter"]
number_sections: true
toc: false
latex_engine: xelatex
classoption: twoside
keep_tex: true
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(knitr)
library(kableExtra)
library(dplyr, quietly=T)
library(tidyr)
```
```{r prox}
column1 <- c("Bert", "Angela", "Nico", "Pam", "Max")
column2 <- c(33, 54, 85, 96, 57)
prox <- data.frame(column1, column2)
prox[nrow(prox)+1, ] <- c('Total', sum(prox$column2))
kable(prox, booktabs = T, linesep = "",
col.names = c("Name", "Count"),
caption = "Number of items") %>%
kable_styling(latex_options = "striped", position = "float_right") %>%
row_spec(5, hline_after = T) %>%
row_spec(6, bold = T)
```
R studio and tinytex are updated. I tried all the debugging tips and uninstalled and installed tinytex new. The same error is also happening when I try to knit on another computer. I also tried to change from xelatex to pdflatex but the error was the same.
The wrapfig package does not particular like zero width wrapfigure or -table environments with captions. Unfortunately that's the width rmarkdown seems to use by default.
The package documentation has the following to say about the topic:
[...] However, if you specify a width of zero (0pt), the actual width of the figure will determine the wrapping width. A following \caption should have the same width as the figure, but it might fail badly; it is safer to specify a width when you use a caption.
You can avoid the problem by choosing a suitable width:
---
title: "Chapter 5"
author: "Moiken Hinrichs"
date: "`r format(Sys.time(), '%d.%m.%Y')`"
header-includes:
- \usepackage{caption}
- \usepackage{float}
- \captionsetup[figure]{font=footnotesize}
- \usepackage{subfig}
- \usepackage{flafter}
- \usepackage{footmisc}
- \usepackage{lipsum}
output:
bookdown::pdf_document2:
extra_dependencies: ["flafter"]
number_sections: true
toc: false
latex_engine: xelatex
classoption: twoside
keep_tex: true
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(knitr)
library(kableExtra)
library(dplyr, quietly=T)
library(tidyr)
```
```{r prox}
column1 <- c("Bert", "Angela", "Nico", "Pam", "Max")
column2 <- c(33, 54, 85, 96, 57)
prox <- data.frame(column1, column2)
prox[nrow(prox)+1, ] <- c('Total', sum(prox$column2))
kable(prox, booktabs = T, linesep = "",
col.names = c("Name", "Count"),
caption = "Number of items") %>%
kable_styling(latex_options = "striped", position = "float_right", wraptable_width = "3cm") %>%
row_spec(5, hline_after = T) %>%
row_spec(6, bold = T)
```
\lipsum
---
title: "Annual Report"
author: "Xyz"
date: "`r format(Sys.time(),'%d %B, %Y')`"
output:
bookdown::pdf_document2:
extra_dependencies: ["float"]
number_sections: false
toc: false
linkcolor: blue
---
```{r, echo = FALSE}
library(ggplot2)
data(mtcars)
names(mtcars)
```
### Heading 1
```{r figure-1,echo=FALSE, fig.cap = "Sample Graph 1"}
ggplot(mtcars,aes(x=mpg,y=hp))+
geom_point()+
theme_classic()
```
To see another graph, please see figure \textcolor{blue}{\#ref(fig:figure-2)}
\newpage
### Heading 2
```{r figure-2,echo=FALSE, fig.cap = "Sample Graph 2"}
ggplot(mtcars,aes(x=mpg,y=carb))+
geom_point()+
theme_classic()
```
To see another graph, please see figure \#ref(fig:figure-1)
After execution, I found the following in knitted pdf document before Heading 2.
To see another graph, please see figure reffig:figure-2
reffig:figure in the code is not cross-referenced as well. What I want is that my document should show the following line in the pdf document:
To see another graph, please see figure 2
"2" in the above statement should be hyperlinked and its color should be blue, enabling the reader to jump to figure 2 if user clicks on "2".
Adding urlcolor:blue to your yaml should work.
---
title: "Annual Report"
author: "Xyz"
date: "`r format(Sys.time(),'%d %B, %Y')`"
output:
bookdown::pdf_document2:
extra_dependencies: ["float"]
number_sections: false
toc: false
linkcolor: blue
urlcolor: blue
---
Original answer found here: R markdown link is not formatted blue when knitted to pdf
I am trying to use the checkmark unicode character (\u2713) in a table rendered by kable in a bookdown project. A MWE consists in the following 2 files (index.Rmd, preamble.tex) part of the generated minimal bookdown project.
index.Rmd
---
title: "A Minimal Book Example"
subtitle: "subtitle"
lang: fr
author: "Yihui Xie"
date: "`r Sys.Date()`"
site: bookdown::bookdown_site
documentclass: book
mainfont: Arial
mathfont: Arial
bibliography: [book.bib, packages.bib]
biblio-style: apalike
link-citations: yes
subparagraph: yes
description: "This is a minimal example of using the bookdown package to write a book. The output format for this example is bookdown::gitbook."
---
```{r setup, include=FALSE}
# Set locale to french for month and day names (calendar plots)
Sys.setlocale(locale = 'French')
# Load all needed libraries
if(!require('pacman'))install.packages('pacman')
pacman::p_load(kableExtra)
```
(ref:O3) O~3~
# Prerequisites
✓
```{r stations-polluants, echo=FALSE}
stations_polluants_table <- data.frame(
stations = c("41B001", "41B004", "41B011", "41MEU1", "41N043", "41R001", "41R002", "41R012", "41WOL1", "Total / polluant"),
O3 = c("", rep("✓", 5), "", rep("\u2713", 2), "7")
)
kable(stations_polluants_table, col.names = c("Station", "(ref:O3)"), booktabs = T, align = "c", caption = "Caption text") %>%
row_spec(0, bold = T) %>%
row_spec(10, bold = T) %>%
collapse_rows(columns = 1, latex_hline = "major", valign = "top")
```
```{r include=FALSE}
# automatically create a bib database for R packages
knitr::write_bib(c(
.packages(), 'bookdown', 'knitr', 'rmarkdown'
), 'packages.bib')
```
preamble.tex
\usepackage{booktabs}
\newfontfamily{\unicodefont}{Arial Unicode MS}
\usepackage{newunicodechar}
\newunicodechar{✓}{{\unicodefont{✓}}}
By compiling in PDF with rmarkdown::render_site(output_format = 'bookdown::pdf_book', encoding = 'UTF-8') one can notice that ✓ is correctly rendered in the text, while it is replaced by <U+2713> in the generated table. I also tried to use \u2713 in the table without more success.
What am I doing wrong ? Please note that, even if the prefered output is PDF, I would also like to compile as gitbook (so Rmd files need to stay independent from the output format).
Many thanks.
After having a moment of clarity, the solution simply lies in using text references in bookdown, i.e. (ref:check) ✓ and use the reference within the table.
index.Rmd
```{r setup, include=FALSE}
# Set locale to french for month and day names (calendar plots)
Sys.setlocale(locale = 'French')
# Load all needed libraries
if(!require('pacman'))install.packages('pacman')
pacman::p_load(kableExtra)
```
(ref:O3) O~3~
# Prerequisites
✓
(ref:check) ✓
```{r stations-polluants, echo=FALSE}
stations_polluants_table <- data.frame(
stations = c("41B001", "41B004", "41B011", "41MEU1", "41N043", "41R001", "41R002", "41R012", "41WOL1", "Total / polluant"),
O3 = c("", rep("(ref:check)", 5), "", rep("(ref:check)", 2), "7")
)
kable(stations_polluants_table, col.names = c("Station", "(ref:O3)"), booktabs = T, align = "c", caption = "Caption text") %>%
row_spec(0, bold = T) %>%
row_spec(10, bold = T) %>%
collapse_rows(columns = 1, latex_hline = "major", valign = "top")
```
```{r include=FALSE}
# automatically create a bib database for R packages
knitr::write_bib(c(
.packages(), 'bookdown', 'knitr', 'rmarkdown'
), 'packages.bib')
```
I have a basic reproducible example here that I think might just be a package limitation. I was wondering if I am just doing something wrong? They both plot fine separately but when combined in the same markdown make the dashboard unable to correctly render.
---
title: "Untitled"
output:
flexdashboard::flex_dashboard:
orientation: rows
source_code: embed
runtime: shiny
---
```{r setup, include=FALSE}
library(tidyverse)
library(plotly)
library(albersusa)
state_sf <- usa_sf("aeqd")
state_dat <- data.frame(state = c("Washington", "Wyoming","Texas","California"), pct = c(0.3,0.5,0.8,0.1))
state_map <- state_sf %>%
left_join(state_dat, by = c("name" = "state"))
```
Test
=====================================
Sidebar {.sidebar data-width=200}
-------------------------------------
Testing
Row
-----------------------------------------------------------------------
###Plotly
```{r graph 1, fig.height=4, fig.width=6}
#Symptoms by state last week===================================================
ggplotly(
ggplot(data = state_map) +
geom_sf(aes(fill=pct))
)
```
###Bar
```{r graph 2, fig.height=4, fig.width=3}
ggplot(data=state_dat) +
geom_col(aes(state,pct,fill=pct))
```
If you are using runtime: shiny you need to use the proper type of Shiny's renderX() functions for each type of plot object to display properly. I don't know why only one plot chunk (w/o renderX()) works, but two breaks it.
### Plotly
```{r graph_1, fig.height=4, fig.width=3}
#Symptoms by state last week
renderPlotly({
ggplotly(
ggplot(data = state_map) +
geom_sf(aes(fill=pct))
)
})
```
### Bar
```{r graph_2, fig.height=4, fig.width=3}
renderPlot({
ggplot(data=state_dat) +
geom_col(aes(state,pct,fill=pct))
})
```
I'm trying to download report form shiny app using R Markdown, but I'm lost! I need to pass a plot from shiny as parameter to R Markdown, and then, include this plot in my report.
I searched a lot about this, but I couldn't find anything. How can I plot this in my report?
Server.R
lm_dif_filter <- reactive({
lm_dif_corn[(lm_dif_corn$farmer == input$farmer) & (lm_dif_corn$Treat_X == 'Farmer'),]
})
output$difPlot <- renderPlotly({
dif <- ggplot(data=lm_dif_filter(), aes(x=Treat_Y, y=dif)) +
geom_bar(stat="identity",color = 'black', position=position_dodge(), width = 0.7)+
geom_hline(yintercept = 0) +
#annotate("text", min(Treat_Y), 0, vjust = -1, label = "Farmer")+
theme(legend.position = "none") +
labs(x = "Treats", y = "Diff")
ggplotly(dif)
To download:
output$report <- downloadHandler(
filename = "report.pdf",
content = function(file) {
tempReport <- file.path(tempdir(), "report.Rmd")
file.copy("report.Rmd", tempReport, overwrite = TRUE)
# Set up parameters to pass to Rmd document
params <- list(set_subtitle = input$farmer, plot = output$difPlot)
rmarkdown::render(tempReport, output_file = file,
params = params,
envir = new.env(parent = globalenv())
)
}
)
My report.rmd
---
title: "Some title"
params:
set_subtitle: test
plot: NA
subtitle: "`r params$set_subtitle`"
date: '`r format(Sys.Date(), "%B %d, %Y")`'
output:
pdf_document:
toc: yes
header-includes:
- \usepackage{fancyhdr}
always_allow_html: yes
---
\addtolength{\headheight}{1.0cm}
\pagestyle{fancyplain}
\lhead{\includegraphics[height=1.2cm]{bg.png}}
\renewcommand{\headrulewidth}{0pt}
```{r, include=FALSE}
options(tinytex.verbose = TRUE)
knitr::opts_chunk$set(echo = FALSE)
cat(params$plot)
One easy option is to not pass the plot, and instead pass the parameter, and refer to a shared plot function used by the shiny app and Rmd doc. For example,
Shiny app,
note the source("util.R") and report_hist(params$n)
source("util.R")
library(shiny)
shinyApp(
ui = fluidPage(
sliderInput("slider", "Slider", 1, 100, 50),
downloadButton("report", "Generate report"),
plotOutput("report_hist")
),
server = function(input, output) {
output$report_hist <- renderPlot({
report_hist(n = input$slider)
})
output$report <- downloadHandler(
# For PDF output, change this to "report.pdf"
filename = "report.html",
content = function(file) {
# Copy the report file to a temporary directory before processing it, in
# case we don't have write permissions to the current working dir (which
# can happen when deployed).
tempReport <- file.path(tempdir(), "report.Rmd")
file.copy("report.Rmd", tempReport, overwrite = TRUE)
# Set up parameters to pass to Rmd document
params <- list(n = input$slider)
# Knit the document, passing in the `params` list, and eval it in a
# child of the global environment (this isolates the code in the document
# from the code in this app).
rmarkdown::render(tempReport, output_file = file,
params = params,
envir = new.env(parent = globalenv())
)
}
)
}
)
Rmd report,
note the report_hist(params$n)
---
title: "Dynamic report"
output: html_document
params:
n: NA
---
```{r}
# The `params` object is available in the document.
params$n
```
A plot of `params$n` random points.
```{r}
report_hist(params$n) #note this function was created in util.R and loaded by the shiny app.
```
Shared function in util.R
report_hist <- function(n){
hist(rnorm(n))
}
Here's a demo shiny app you can test it out with, https://rstudio.cloud/project/295626