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

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.

Related

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
---

Printing formatted markdown text with Officedown knit_print_block

I'm using the officedown function knit_print_block to print figure captions in Rmarkdown, with MS Word output. This is needed because I'm looping through lots of figures, and need each to return the captioned figure, as well as a cross-reference.
All's well with plain text. I can get the caption printed, and have a cross-reference object as well. However, if I try to use basic markdown formatting (in this case to superscript a value), such as t/nmi^2^, this does not return a superscript in the Word document. I have tried to return XML text as well (as documentation onknit_print_block states 'the function only print XML code') but do not return a superscripted value. Below is a minimal .Rmd example. It simply uses the mtcars dataset to make a meaningless plot, and then tries to return captions and bookmarks.
---
output: officedown::rdocx_document
---
```{r setup, include=FALSE}
library(officedown)
library(officer)
library(ggplot2)
```
```{r, echo = FALSE, message=FALSE, warning=FALSE, fig.width= 7, fig.height= 4, results = 'asis'}
for (i in 1:2){
#make a placeholder plot
tmp_plot = ggplot(mtcars, aes(x = mpg , y = hp )) +
geom_point()
print(tmp_plot)
#build the caption
cap_text = paste0('Density (t/nmi^2^) in sample ', i)
#build the bookmark
fig_name = paste0('samplesummary', i)
#build the caption
tmp_fig_caption = block_caption(cap_text,
style = 'Normal',
autonum = run_autonum(seq_id = 'fig',
pre_label = "Figure ",
bkm = fig_name))
#print caption
officedown::knit_print_block(tmp_fig_caption)
}
```
Just some normal text. Are cross-refernces returned? Yep: Figure\#ref(fig:samplesummary1), Figure \#ref(fig:samplesummary2)

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

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?"
)
```

Rmarkdown officer / officedown / flextables problem

I have the following rmd script. I've spent a few days trying to get this to work but I am failing miserably. Basically I need help with three things. I am happy to post three separate questions if needed.
The multicolumn options/code are completely ignored. The corporatetable.docx is in landscape and has a typical corporate style. I need to have a full width landscape -> two column landscape -> full width landscape. If I could get the two column landscape setup to work, the remaining style would be inherited by corporatetable.docx. If I could get help with only one - I would need this.
When I run the rmd it generates a word file but none of the corporate styles are in there. It just uses my word's default colors etc. The difference is very clear - no landscape, single column and blue instead of red. How do I correctly pass the officedown::rdocx_document: to reference my word file because it's clearly not picking it up and no warning or error is generated?
If you see in the second chunk I am using flextable to show two pictures (which are passed through params) in the word report and align them with some information. myft works but it prints the (temporary/volatile) path instead of showing the pictures in the report. For reference if I use knitr::include_graphics(c(params$x1,params$x2)) it works fine.
I'm really stuck on these. Any help is welcome.
---
title: "Title"
subtitle:
params:
x1: x1
x1_name: x1_name
x1_email : x1_email
x2: x2
x2_name: x2_name
x2_email : x2_name
output:
officedown::rdocx_document:
reference_docx: corporatetemplate.docx
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(officedown)
library(officer)
library(flextable)
knitr::opts_chunk$set(out.width = '100%', dpi=300)
```
<!---BLOCK_MULTICOL_START--->
This text is on column 1. Please work
```{r somecodechunk, echo=FALSE, out.width="75px", include=TRUE, strip.white=TRUE}
library(flextable)
# this works but prefer to use flextable
# if(all(!is.null(params))) {
# knitr::include_graphics(c(params$x1,params$x2))} else {
# }
myft <- data.frame(
"pic1" = rep("",3),
"details1" = c(params$x1_name,"+X XXX XXX X",params$x1_email),
"pic2" = rep("",3),
"details2" = c(params$x2_name,"+X XXX XXX X",params$x2_email)
)
myft <- flextable(myft)
myft <- merge_at(myft, i = 1:3, j = 1 )
myft <- merge_at(myft, i = 1:3, j = 3 )
myft <- compose(myft,i = 1, j = 1, value = as_paragraph(as_image(params$x1), part = "body"))
myft <- compose(myft,i = 1, j = 3, value = as_paragraph(as_image(params$x2), part = "body"))
autofit(myft)
#Ok this does not work because the pics are not shown
```
`r run_columnbreak()`
This text is on column 2. Please work
This text is on column 2. Please work
`r run_linebreak()`
<!---BLOCK_MULTICOL_STOP{widths: [4,4], space: 0.2, sep: true}--->
\pagebreak
Back to full width with some text
\pagebreak

Restart Figure Numbering for Appendix / Supplementary Material in bookdown

I am writing an article for a journal that requires Supplementary Material. I was hoping to use a unique label such as SuppMat: instead of the default fig: to send Figures and Tables into this section. If not, I can use the default fig label but I need numbering to restart in the Supplementary Material section of the document.
I am aware of one answer using latex (found here) but I must complete this when exporting to docx. Below is a reproducible example using officedown
---
output:
officedown::rdocx_document
---
```{r setup, include=FALSE}
pacman::p_load(knitr, officedown, officer)
knitr::opts_chunk$set(echo = FALSE,
eval = TRUE,
fig.cap = TRUE)
```
# Main Text
Please see Supplementary Figure \#ref(fig:appendix-fig1) and Figure \#ref(fig:main-fig1).
```{r fig.id="main-fig1", fig.cap="This should be labelled **Figure 1**"}
barplot(1:5, col=1:5)
```
```{r tab.id="main-tab1", tab.cap="Main Text Table 1"}
head(mtcars)
```
\newpage
# Supplementary Materials {#SuppMat}
```{r fig.id="appendix-fig1", fig.cap="This figure should be labelled **Supplementary Figure 1**"}
barplot(1:5, col=1:5)
```
```{r tab.id="appendix-tab1", tab.cap="Should be labelled **Supplementary Table 1**"}
head(mtcars)
```
After searching multiple forums and hours, I was able to come up with a solution using the officedown package. Hopefully this helps someone else out. For further details check out the run_autonum function.
---
output: officedown::rdocx_document
---
```{r setup, include=FALSE}
pacman::p_load(officedown, officer, knitr)
knitr::opts_chunk$set(echo = FALSE, fig.cap = TRUE)
ft_base <- fp_text(font.family = "Cambria", font.size = 12, bold = TRUE)
ft1 <- update(ft_base, shading.color='#EFEFEF', color = "red")
ft2 <- update(ft_base, color = "#C32900")
srcfile <- file.path( R.home("doc"), "html", "logo.jpg" )
extimg <- external_img(src = srcfile, height = 1.06/5, width = 1.39/5)
```
## References
This is a reference to an supplementary image caption whose number is Supplementary Figure \#ref(fig:faithfuld-plot) and \#ref(fig:supp-bar).
Testing another figure with a barplot in Figure \#ref(fig:plotbar)
```{r fig.id="plotbar", fig.cap = "Main Figure"}
barplot(1:8, col=1:2)
```
## Supplementary Material
```{r fig.id="faithfuld-plot"}
knitr::include_graphics("images/MyImage.png") # Use your own figure here (I needed to test with knitr for my workflow)
block_caption("First Appendix Figure",
style = "Figure",
autonum = run_autonum(seq_id = 'fig',
bkm = 'faithfuld-plot',
pre_label = "Supplemental Figure ",
start_at=1))
```
```{r fig.id="supp-bar"}
barplot(1:8, col=1:2)
block_caption("Second Appendix Figure",
style = "Figure",
autonum = run_autonum(seq_id = 'fig',
bkm = 'supp-bar',
pre_label = "Supplemental Figure ",
start_at= NULL))
```