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)
Related
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
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.
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!
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))
```
I am using RStudio to write my R Markdown files. How can I remove the hashes (##) in the final HTML output file that are displayed before the code output?
As an example:
---
output: html_document
---
```{r}
head(cars)
```
You can include in your chunk options something like
comment=NA # to remove all hashes
or
comment='%' # to use a different character
More help on knitr available from here: http://yihui.name/knitr/options
If you are using R Markdown as you mentioned, your chunk could look like this:
```{r comment=NA}
summary(cars)
```
If you want to change this globally, you can include a chunk in your document:
```{r include=FALSE}
knitr::opts_chunk$set(comment = NA)
```
Just HTML
If your output is just HTML, you can make good use of the PRE or CODE HTML tag.
Example
```{r my_pre_example,echo=FALSE,include=TRUE,results='asis'}
knitr::opts_chunk$set(comment = NA)
cat('<pre>')
print(t.test(mtcars$mpg,mtcars$wt))
cat('</pre>')
```
HTML Result:
Welch Two Sample t-test
data: mtcars$mpg and mtcars$wt
t = 15.633, df = 32.633, p-value < 0.00000000000000022
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
14.67644 19.07031
sample estimates:
mean of x mean of y
20.09062 3.21725
Just PDF
If your output is PDF, then you may need some replace function. Here what I am using:
```r
tidyPrint <- function(data) {
content <- paste0(data,collapse = "\n\n")
content <- str_replace_all(content,"\\t"," ")
content <- str_replace_all(content,"\\ ","\\\\ ")
content <- str_replace_all(content,"\\$","\\\\$")
content <- str_replace_all(content,"\\*","\\\\*")
content <- str_replace_all(content,":",": ")
return(content)
}
```
Example
The code also needs to be a little different:
```{r my_pre_example,echo=FALSE,include=TRUE,results='asis'}
knitr::opts_chunk$set(comment = NA)
resultTTest <- capture.output(t.test(mtcars$mpg,mtcars$wt))
cat(tidyPrint(resultTTest))
```
PDF Result
PDF and HTML
If you really need the page work in both cases PDF and HTML, the tidyPrint should be a little different in the last step.
```r
tidyPrint <- function(data) {
content <- paste0(data,collapse = "\n\n")
content <- str_replace_all(content,"\\t"," ")
content <- str_replace_all(content,"\\ ","\\\\ ")
content <- str_replace_all(content,"\\$","\\\\$")
content <- str_replace_all(content,"\\*","\\\\*")
content <- str_replace_all(content,":",": ")
return(paste("<code>",content,"</code>\n"))
}
```
Result
The PDF result is the same, and the HTML result is close to the previous, but with some extra border.
It is not perfect but maybe is good enough.