Flextable table links not linking to my tables - r-markdown

I have generated tables in docx using Rmarkdown (Output: word_document), with captions and links to the tables. For some reason clicking on the links takes me to the top of my word file and not to the relevant table.
Here is some example code: #first time having an rmarkdown related issue, please bare with me
library(officer)
library(flextable)
library(knitr)
library(magrittr)
# set chunks defaults
knitr::opts_chunk$set(echo=FALSE, message=FALSE, warning=FALSE)
#create example df
df1 <- data.frame(col1=c("a","b","c"),
col2=c("1","2","3"))
df2 <- data.frame(col1=c("d","e","f"),
col2=c("4","5","6"))
(Link to table 2) <--- this link should take me to flextable 2, but it doesn't.
#create flextable 1
ft1 <- flextable(df1)
ft1 <- set_caption(ft1, "Caption 1.",
style = "Table Caption",
autonum = run_autonum(seq_id = "tab",bkm="tab1"))
ft1
(Link to Table 1) <---- This link should take me to table 1, but it doesn't.
I set these links in this order to hopefully make the problem clearer.
#links created using format [(Link)](#tab:tab2)
#second flextable
ft2 <- flextable(df2)
ft2 <- set_caption(ft2, "Caption 2.",
style = "Table Caption",
autonum = run_autonum(seq_id = "tab",bkm="tab2"))
ft2
if this is possible using flextable, I am probably making a small mistake somewhere, but can't spot it. So far this is the only function I found that renders docx table output using Rmarkdown
Please help.

I made this example for you:
---
title: "Untitled"
author: "Your Name"
date: "December 16, 2021"
output:
bookdown::word_document2: default
---
```{r setup}
library(flextable)
#create example df
df1 <- data.frame(col1=c("a","b","c"),
col2=c("1","2","3"))
df2 <- data.frame(col1=c("d","e","f"),
col2=c("4","5","6"))
```
```{r Table1}
ft1 <- flextable(df1)
set_caption(ft1, "I love R language")
```
\newpage
```{r Table2}
ft2 <- flextable(df2)
set_caption(ft2, "I hope, it loves me too")
```
\newpage
[(Click, here is the first table)](#tab:Table1)
[(Here is the second)](#tab:Table2)
Good luck and the big success in the process of R learning to you;)
An addition:
```{r Table3, tab.cap = "An another table"}
flextable(df2)
```
\newpage
Ok, here is a third table [(Here is the third)](#tab:Table3).

For anyone else that might run into this problem.
Using the example #manro made above, I got it to work by editing the YAML.
title: "Untitled"
author: "Your Name"
date: "December 16, 2021"
output:
officedown::rdocx_document:
reference_docx: template.docx
library(flextable)
library(officedown)
library(officer)
#create example df
df1 <- data.frame(col1=c("a","b","c"),
col2=c("1","2","3"))
df2 <- data.frame(col1=c("d","e","f"),
col2=c("4","5","6"))
ft1 <- flextable(df1)
set_caption(ft1, "I love R language")
\newpage
ft2 <- flextable(df2)
set_caption(ft2, "I hope, it loves me too")
\newpage
And by removing "tab:" from [(Link)](#tab:tab2) from the link examples below.
[(Click, here is the first table)](#tab:Table1)
[(Here is the second)](#tab:Table2)
leaving me with.
[(Click, here is the first table)](#Table1)
[(Here is the second)](#Table2)

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

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

Auto-Numbering of Figure and Table Captions for HTML Output in R Markdown

Is there a way to automatically number the figures in captions when I knit R Markdown document into an HTML format?
What I would like is for my output to be the following:
Figure 1: Here is my caption for this amazing graph.
However, I am currently getting the following:
Here is my caption for this amazing graph.
Here is my MWE:
---
title: "My title"
author: "Me"
output:
html_document:
number_sections: TRUE
fig_caption: TRUE
---
```{r setup}
knitr::opts_chunk$set(echo=FALSE)
```
```{r plot1,fig.cap="Here is my caption for this amazing graph."}
x <- 1:10
y <- rnorm(10)
plot(x,y)
```
```{r table1, fig.cap="Here is my caption for an amazing table."}
head(mtcars, 2)
```
I have read that this issue is resolved with Bookdown but I've read the Definitive Guide to Bookdown, cover to cover, and can't find it.
If you wish to have numbered figures, you will need to use an output format provided by bookdown. These include html_document2, pdf_document2 etc. See here for a more comprehensive list of options.
Changing your document example html_document to bookdown::html_document2 will resolve your problem.
---
title: "My title"
author: "Me"
output:
bookdown::html_document2:
number_sections: TRUE
fig_caption: TRUE
---
```{r setup}
knitr::opts_chunk$set(echo=FALSE)
```
```{r plot1,fig.cap="Here is my caption for this amazing graph."}
x <- 1:10
y <- rnorm(10)
plot(x,y)
```
```{r plot2, fig.cap="Here is my caption for another amazing graph."}
plot(y,x)
```
If you want to label tables created by knitr::kable, you will need to specify the caption within the table call itself
```{r table1}
knitr::kable(mtcars[1:5, 1:5], caption = "Here is an amazing table")
```

How to rotate or adjust a big table in Rmarkdown?

Here is my example:
---
title: "There is a reproductible example"
output: pdf_document
---
```{r table-simple, echo=FALSE, message=FALSE, warnings=FALSE, results='asis'}
require(pander)
panderOptions('table.split.table', Inf)
set.caption("My great data")
my.data <- " # replace the text below with your table data
Anticonstitutionnellement|Anticonstitutionnellement|Anticonstitutionnellement|Anticonstitutionnellement|Anticonstitutionnellement
Anticonstitutionnellement|Anticonstitutionnellement|Anticonstitutionnellement|Anticonstitutionnellement|Anticonstitutionnellement
Anticonstitutionnellement|Anticonstitutionnellement|Anticonstitutionnellement|Anticonstitutionnellement|Anticonstitutionnellement
Anticonstitutionnellement|Anticonstitutionnellement|Anticonstitutionnellement|Anticonstitutionnellement|Anticonstitutionnellement "
df <- read.delim(textConnection(my.data),header=FALSE,sep="|",strip.white=TRUE,stringsAsFactors=FALSE)
names(df) <- unname(as.list(df[1,])) # put headers on
df <- df[-1,] # remove first row
row.names(df)<-NULL
pander(df, style = 'rmarkdown')
```
In the final PDF outputs, Words overlap.
I use "kable", "table", "print"
Do you have an idea that the words do not overlap?
If the table is very huge, I want that the table rotate automatically in landscape format. Is it possible?
You could try to add the option:
classoption: landscape
in your head section
---
title: "There is a reproductible example"
output: pdf_document
classoption: landscape
---
This will produce a landscape version of the document.

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=",")
})