Knit a kable to PDF in RMarkdown that includes special characters in the table values - r-markdown

I'm trying to format a kable that includes the permyriad sign "‱". Permyriad means 1 out of every 10,000, so 1‱ = 0.01%.
I can get it to work with the special character σ, as in the screenshot and code below. Looking for a way to replace "σ" replaced with "‱".
I am pretty sure that there exists a magical combination of the three variables what_should_this_be, should_i_escape_or_not, and id_like_to_use_booktabs that will do the trick.
I'm doing this within RStudio using the tinytex package.
Here's what I've attempted so far:
The exact value for the variable what_should_this_be that results in knitting the ‱ sign in the final pdf. The Unicode value for "‱" is U+2031.
Values I've tried:
Combinations of "\textperthousand" with varying numbers of escapes, with and without brackets, with and without opening & closing $
Copy-pasting the ‱ symbol directly with varying numbers of escapes
"\U2031" with varying numbers of escapes
Various combinations with should_i_escape_or_not set to TRUE or FALSE.
I'd like to use booktabs... but that might be asking a bit much, so I've tried various combinations setting id_like_to_use_booktabs to TRUE or FALSE.
Various combinations of setting the "Typeset LaTeX into PDF using:" option in RStudio > Tools > Sweave
```{r, echo = FALSE}
library(magrittr)
what_should_this_be <- "$\\sigma$"
should_escape_or_not <- FALSE
id_like_to_use_booktabs <- TRUE
knitr::kable(
head(mtcars) %>%
dplyr::select(mpg) %>%
tibble::rownames_to_column("car") %>%
dplyr::mutate(mpg = paste0(mpg, what_should_this_be)),
align = "cc",
escape = should_escape_or_not,
booktabs = id_like_to_use_booktabs,
caption = "Works with character $\\sigma$, but what about permyriad?"
)
```

Could use the textcomp package and \textpertenthousand
---
output:
pdf_document:
latex_engine: xelatex
header-includes:
- \usepackage{textcomp}
---
```{r, echo = FALSE}
library(magrittr)
what_should_this_be <- "\\textpertenthousand"
knitr::kable(
head(mtcars) %>%
dplyr::select(mpg) %>%
tibble::rownames_to_column("car") %>%
dplyr::mutate(mpg = paste0(mpg, what_should_this_be)),
align = "cc",
escape = F,
booktabs = T,
caption = "Works with character $\\sigma$, but what about permyriad?"
)
```

Related

Word count in Quarto

I would love a convenient and easy way to print my word count automatically in quarto and stumbled across this nice add-in from Ben Marwick:
https://github.com/benmarwick/wordcountaddin
It is sound for rmarkdown and I presumed it should be no issue with quarto too. However, when I use the add-in, though it can count out the number of words within my RStudio session, it doesn't print it in my final pdf format and just returns [1] NA.
{r, #wordcountdev, message = FALSE, warning = FALSE, echo = FALSE}
wordstats <- wordcountaddin:::text_stats('CMI Write Up.qmd')
words <- substr(wordstats[3], start=19, stop=30)
print(words)
I don't understand what is going on here, it is seemingly simple, would anyone know of a better way to achieve what I'm trying?
You could take a look at the wordcounts pandoc filter, e.g. as a starting point it prints the number of words in the body to the console while rendering:
---
format: html
filters: [wordcounts.lua]
---
Hello there, how many words are in the body?
Or: You can use the development version (devtools::install_github("benmarwick/wordcountaddin", type = "source", dependencies = TRUE)) of the above mentioned package:
---
format: html
---
```{r}
#| echo: false
#| label: wordstats
#| warning: false
#| message: false
wordcount <- wordcountaddin::text_stats('wordcount.qmd')
words <- substr(wordcount[3], start=19, stop=30)
```
Hello there, how many words are in the body?
There are `r words` words in the whole document.

How to PDF render Quarto books with dynamic content?

I am writing my thesis using a Quarto book in HTML, which has some dynamic content (leaflet maps, plotly dynamic graphs). However, eventually, I will need to export the book in PDF/LaTeX, or at least Word (and then I can copy and paste into LaTeX).
When I try to export to PDF I of course run into this error:
Functions that produce HTML output found in document targeting pdf
output. Please change the output type of this document to HTML.
Alternatively, you can allow HTML output in non-HTML formats by adding
this option to the YAML front-matter of your rmarkdown file:
always_allow_html: true
Note however that the HTML output will not be visible in non-HTML
formats.
I did try to add the always_allow_html: true in my YAML file, but I get the same exact error. I also tried the conditional rendering with {.content-hidden unless-format="pdf"}, but I can't seem to get it working.
Has anyone experienced the same issue?
Using .content-visible when-format="html" and .content-visible when-format="pdf" works very smoothly.
---
title: "Conditional Rendering"
format:
html: default
pdf: default
---
## Conditional Content in Quarto
::: {.content-visible when-format="html"}
```{r}
#| message: false
library(plotly)
library(ggplot2)
p <- ggplot(mtcars, aes(wt, mpg))
p <- p + geom_point(aes(colour = factor(cyl)))
ggplotly(p)
```
```{r}
#| message: false
#| fig-pos: "H"
#| fig-width: 4
#| fig-height: 3
library(leaflet)
# took this example from leaflet docs
m <- leaflet() %>%
addTiles() %>% # Add default OpenStreetMap map tiles
addMarkers(lng=174.768, lat=-36.852, popup="The birthplace of R")
m # Print the map
```
:::
::: {.content-visible when-format="pdf"}
```{r}
library(plotly)
library(ggplot2)
p <- ggplot(mtcars, aes(wt, mpg))
p <- p + geom_point(aes(colour = factor(cyl)))
p
```
:::
I use constructs like below
p <- ggplot()
if (interactive() || opts_knit$get("rmarkdown.pandoc.to") == "html") {
ggplotly(p)
} else {
p
}
Stumbled across this one too. I'm currently checking the output format of pandoc globally
```{r, echo = F}
output <- knitr::opts_knit$get("rmarkdown.pandoc.to")
```
and then evaluate chunks conditionally:
(leaflet example from here.)
```{r, echo = F, eval = output != "latex"}
library(leaflet)
leaflet() %>%
addTiles() %>% # Add default OpenStreetMap map tiles
addMarkers(lng=174.768, lat=-36.852, popup="The birthplace of R")
```
This is optional if you want a note on a missing component in the PDF version:
```{r, echo = F, eval = output == "latex", results = "asis"}
cat("\\textit{Please see the HTML version for interactive content.}")
```
Edit
I just checked, this also works with Quarto documents for me using the below YAML header.
---
title: "Untitled"
format:
html:
theme: cosmo
pdf:
documentclass: scrreprt
---

how to insert citation in a footnote of table generated with kable?

I was trying to add citation in a footnote (or even in any text in the table) but it's not working, the citation text appears as it is. I thought I need to change the format table to markdown instead of latex and using bookdown::pdf_document2 but both did not solve the problem. another attempt was to create a citation text outside kable with a separate code chunk and then paste it inside the footnote also didn't work.
this is my code:
---
title: "scientific report"
output:
pdf_document:
fig_caption: true
keep_tex: true
number_sections: yes
latex_engine: xelatex
csl: elsevier-with-titles.csl
bibliography: citations.bib
link-citations: true
linkcolor: blue
---
# This is an exaample
the number of the table below is [\ref{do}]
P.S. I wrote the superscript (a) manually in the xlsx file.
```{r echo=FALSE }
library(knitr)
library(kableExtra)
library("readxl")
dfdf <- read_excel("dyss_count.xlsx")
df <- as.data.frame(dfdf)
options(knitr.kable.NA = '')
kable(df, "latex", longtable = T, booktabs = T,escape = F ,caption = 'dosage \\label{do}',align = "c") %>%
kable_styling(latex_options = c('repeat_header'), font_size = 7) %>%
footnote(general ="A general footnote",
alphabet = 'the source is #Burg_2019',
general_title = "General: ", number_title = "Type I: ",
alphabet_title = "Type II: ",
footnote_as_chunk = T, title_format = c("italic", "underline")
)
result is:
I would be very thankful for any useful information.
well, after many attempts it worked with the conventional cross referencing here. so
in case someone else is having same issue, I just did this:
(ref:caption) The source is [#Burg_2019] outside the the chunk and then inside the footnote footnote(general ="A general footnote",alphabet = "(ref:caption)" )
You could possible try adding in a caption using css -> kable_styling(extra_css = ..) so you could modify its styling properties? Just a thought.

How to format a table with embedded images to pdf format using rmarkdown?

I have written a script to generate an rmarkdown report that appends a QR Code containing a numerical result to a dataframe when outputting to a pdf format in kable (see my associated post here). The QC Codes are generated as a vector of images and are appended to a new column in the dataframe when the report is generated.
This works fine, however to output the table in .pdf format, I have to set kable(df, format = "markdown"), otherwise the image of the QR Code doesn't get placed in the output table, just the file path text. This works fine except if I want to modify the table using kableExtra format options, which require the kable format to be latex.
In the example code I have listed below, you can see that when kable(df, format = "markdown") the images are formatted correctly but the kableExtra formatting doesn't work. Conversely, when the kable(df, format = "latex") the kableExtra format options work, but the images do not.
---
title: "QR Code in Column"
author: "me"
date: "2019/01/20"
output: pdf_document
---
```{r mychunk, echo = FALSE, fig.path = "qr/", results = 'asis', fig.show='hide'}
library(knitr)
library(qrcode)
library(kableExtra)
df <- data.frame(test = LETTERS[1:2],
result = as.character(round(rnorm(2), 2)),
stringsAsFactors = F)
res.qr <- lapply(df$result, function(qr) {
qrcode_gen(qr) # create qrcodes
nrow(qr) # save number of rows of df
})
path <- paste0(opts_current$get("fig.path"), opts_current$get("label"), "-")
total <- 0
df$Code <- paste0("![](", path, (1:length(res.qr)) + total, ".pdf){width=72px}")
```
```{r echo = FALSE}
# This example works to generate the desired output, but the kableExtra options won't work.
kable(df, format = "markdown") %>%
add_header_above(c(" ", "Class 1" = 2))
```
```{r echo = FALSE}
# This example works to use the kableExtra formatting options, but the QR Code isn't an image.
kable(df, format = "latex") %>%
add_header_above(c(" ", "Class 1" = 2))
```
I would like to be able to format the output table in the .pdf file using kableExtra, however I am open to any other options that may work!

R Markdown Table 1000 separator

I am trying to publish a table with 1000 separators and I am not having any luck with it. I followed the link here: Set global thousand separator on knitr but am not having much success.
My sample dataset is here: https://goo.gl/G7sZhr
The RMarkdown code is here:
---
title: "Table Example"
author: "Krishnan Viswanathan"
date: "August 4, 2015"
output: html_document
---
Load Data
{r, results='asis', message = FALSE, tidy=TRUE}
load("i75_from_flow.RData")
library(data.table)
{r, results='asis', echo=FALSE,message = FALSE, tidy=TRUE}
i75_from_flow <- i75_from_flow[order(-Tons),]
knitr::kable(i75_from_flow)
However, when I include this chunk of code (knit_hook$set) in the RMarkdown document, i get errors.
```{r, results='asis', echo=FALSE,message = FALSE, tidy=TRUE}
i75_from_flow <- i75_from_flow[order(-Tons),]
knit_hooks$set(inline = function(x) {
prettyNum(x, big.mark=",")
})
knitr::kable(i75_from_flow)
```
Error:
# object knit_hooks not found.
Any insights on what I am doing wrong and how to fix this is much appreciated.
Thanks,
Krishnan
The easiest is to use the format arguments of the kable() function itself, where you can specify the big number mark like so:
kable(df, format.args = list(big.mark = ","))
So your example would look like:
```{r, results='asis', echo=FALSE,message = FALSE, tidy=TRUE}
i75_from_flow <- i75_from_flow[order(-Tons),]
knitr::kable(i75_from_flow, format.args = list(big.mark = ","))
```
without any need for knitr hooks.
What about using pander with bunch of options to fine-tune your markdown table:
> pander::pander(i75_from_flow, big.mark = ',')
----------------------------
ORIGFIPS TERMFIPS Tons
---------- ---------- ------
12,023 12,117 5,891
12,119 12,105 4,959
12,001 12,057 3,585
12,001 12,113 3,083
12,047 12,047 1,517
----------------------------
The reason that the knit_hooks object is not found is that you either need to load the knitr package or use the knitr:: prefix in order to set the knit_hooks options. For example:
knitr::knit_hooks$set(inline = function(x) {
prettyNum(x, big.mark=",")
})