Internationalization R knitr Figure caption label - r

I want to generate a Latex document with knitr, but it does not allow me to change the label for the figure into my language. The code:
```{r rstudio, echo = FALSE, fig.cap = "RStudio IDE", fig.margin = T}
plot(pressure)
```
This generates:
However I want the caption label to read Figura: (portuguese) instead of Figure: . I added the variable lang: pt-br, which corrects for when I call it with \#ref(fig:rstudio), but does not fixes the figure label.
How to change the caption label in Rmarkdown?

You can actually include LaTeX code directly within the Rmd file to alter the settings.
As this answer explains, names like "Figure" and "Contents" are stored in macros like \figurename and \contentsname. To change them, you have to change the definition of the respective macros using \renewcommand within your preamble:
\renewcommand{\figurename}{Fig.}
\renewcommand{\contentsname}{Table of Contents}
Here's a list of the "name macros" (and their default meaning) defined by the LaTeX standard classes article, book, and report:
\abstractname [only article, report]: Abstract
\appendixname: Appendix
\bibname [only book, report]: Bibliography
\chaptername [only book, report]: Chapter
\contentsname: Contents
\figurename: Figure
\indexname: Index
\listfigurename: List of Figures
\listtablename: List of Tables
\partname: Part
\refname [only article]: References
\tablename: Table
Here is a MWE for your scenario:
---
output:
pdf_document: default
---
\renewcommand{\figurename}{YOUR LABEL}
\renewcommand{\tablename}{TABLE LABEL}
```{r Table, echo =FALSE}
knitr::kable(iris[1:5,], caption = "A table")
```
```{r pressure, echo=FALSE, fig.cap="Test Caption"}
plot(pressure)
```
Alternative Approach
The fantastic package bookdown expands a lot on the basics of RMarkdown and knitr. One thing the package allows you to set internalisation, as explained here.

Related

Is there a way to add line breaks ONLY when exporting to PDF in R Markdown?

I think the question is quite self-explanatory but for avoidance of doubt I'll explain with more detail below:
I have an R Markdown document that works well if converted to HTML or uploaded to GitHub. When converting to PDF (using Latex), the results are not so pretty. I find that the biggest problem in a Latex PDF document are line breaks. I can fix the line breaks issue on the PDF document by adding "\ " characters, but that throws my HTML document out of whack too.
Is there a way to manually add line breaks (or "space before/after paragraphs") for the PDF output only?
Thank you!
You can redefine the relevant spacings in the YAML header. \parskip controls the paragraph spacing. Code blocks are shaded using a snugshade environment from the framed package. We can also redefine the shaded environment for code blocks to have some vertical space at the start. Here's a reproducible example. Note: I also added the keep_tex parameter so you can see exactly what the generated tex file looks like, in case this is useful:
title: "test"
author: "A.N. Other"
header-includes:
- \setlength{\parskip}{\baselineskip}
- \renewenvironment{Shaded}{\vspace{\parskip}\begin{snugshade}}{\end{snugshade}}
output:
pdf_document:
keep_tex: true
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.
When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
```{r cars}
summary(cars)
```
## Including Plots
You can also embed plots, for example:
```{r pressure, echo=FALSE}
plot(pressure)
```
Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.
Once you output to HTML, you can just print the HTML webpage as PDF. that might be an easy way keep the original format

Prevent table being split in Rmarkdown

Is there a way to put my table into one page? I have a table which is broken between two pages. Here is a reproducible example:
---
output: pdf_document
---
`r rep("Text", 400)`
```{r}
# This will create a page break
knitr::kable(mtcars, caption = "A split table")
```
This produces a 2 page pdf with a broken table as follows::
There are two easy ways to do this:
1. Add a page break
If you are only using the PDF output, you can actually integrate LaTeX commands directly into the report. Therefore the \newpage command will force a pagebreak as follows:
---
output: pdf_document
---
`r rep("Text", 400)`
\newpage
```{r}
knitr::kable(mtcars, caption = "A fixed table")
```
2. Use Page Floats:
As RMarkdown uses LaTeX to build the PDF, you can take advantage of the page floats feature. This can take some getting used to, but rather than locking the figure or table in a set position, LaTeX will try and place the figure in a position which it deems "best". With tables, it will try and remove any page breaks.
Here is an example. The table will float to the second page. Make sure to update the YAML to include the header-includes: argument as well:
---
output: pdf_document
header-includes:
- \usepackage{booktabs}
---
`r rep("Text", 400)`
```{r}
knitr::kable(mtcars, format = "latex",
caption = "A caption",
booktabs = TRUE,
longtable = FALSE)
```
`r rep("Text", 200)`
If you look at the output, you will see that the second chunk of text continues on the same page as the first, and that the table is centered on the second page. This is all done automatically by LaTeX and can avoid pain down the road if you add more text before the table which might have previously caused the table to be broken again.
Hope that helps.

How to put a crossreference in Rbookdown?

I am not sure I understand this part from the documentation
the table label for a code chunk with the label foo will be tab:foo
Say I have a RMarkdown chunck such as
```{r mytable, echo=FALSE}
kable(df, booktabs=T)
```
I would consider mytabel as the label for the code chunck. That means I should be able to type a narrative that looks like:
This is my table \#ref(tab:mytable)
And the \#ref should reference the table number instead of the chucnk id. Instead I get a double (and clickable) ?? .What am I doing wrong?
In the second paragraph of the documention:
Like figures, tables with captions will also be numbered and can be referenced.
So you want to cross-reference a table, you must specify the caption argument.
You can create a empty RStudio project and or save following code as index.Rmd file. Or download
https://github.com/yihui/bookdown-minimal and replace the content of index.Rmd file with the following code. Then you can press Build Book button in the Build panel.
---
title: "A Book"
author: "Frida Gomam"
site: bookdown::bookdown_site
output:
bookdown::gitbook: default
---
# reference
This is my table \#ref(tab:mytable)
# table
```{r mytable, echo=TRUE}
knitr::kable(iris[1:10, ], booktabs=T, caption='A table of the first 10 rows of the mtcars data')
```

Conditionally display block of markdown text using knitr

I would like to edit a single rmarkdown (Rmd) document with a list of "problems", each followed by its solution. Each solution may contain the results of the R console, but also some explaining (markdown and LaTeX formatted) text. Besides, I would like use knitr in 2 versions: with and without the solutions, changing the source as less as possible, and compiling.
I know that I can use a logical variable in order to conditionally evaluate R code and show plots and R output, but I don't know how to show/hide blocks of (markdown and LaTeX) formatted text, unless I put all that text into R character vectors, which seems hard for keeping things clean and readable.
I found this old question,
Conditionally display a block of text in R Markdown
where the solution was given for simple short text, which was included as an argument of the R print() function.
This other old question,
insert portions of a markdown document inside another markdown document using knitr
was for having a father document and child documents which were conditionally compiled, but I don't want to slice my document into so many pieces.
You could use the asis engine to conditionally include/exclude arbitrary text in knitr, e.g.
```{asis, echo=FALSE}
Some arbitrary text.
1. item
2. item
Change echo=TRUE or FALSE to display/hide this chunk.
```
But I just discovered a bug in this engine and fixed it. Unless you use knitr >= 1.11.6, you can create a simple asis engine by yourself, e.g.
```{r setup, include=FALSE}
library(knitr)
knit_engines$set(asis = function(options) {
if (options$echo && options$eval) paste(options$code, collapse = '\n')
})
```
If you want to include inline R expressions in the text, you will have to knit the text, e.g.
```{r setup, include=FALSE}
library(knitr)
knit_engines$set(asis = function(options) {
if (options$echo && options$eval) knit_child(text = options$code)
})
```
There is a way to hide parts of the document (including text and chunks): to comment them out with html comment marks.
And comment marks can be generated by R in a block according to a variable that can be set at the beginning of the document.
```{r results='asis', echo=FALSE}
if (hide) {cat("<!---")}
```
```{r results='asis', echo=FALSE}
if (hide) {cat("-->")}
```
And just to show a complete working example, in the example below the middle section of the document can be shown or hidden by setting the hide variable to FALSE or TRUE. That might be useful in case there are several sections to hide or show at once - for example, solutions of course problems.
---
title: "Untitled"
date: "15/10/2020"
output:
word_document: default
html_document: default
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
hide <- TRUE #TRUE to comment out part of the document, FALSE to show.
```
## Start
Always shown.
```{r}
hide
```
```{r results='asis', echo=FALSE}
if (hide) {cat("<!---")}
```
## To hide or not to hide
To be hidden or shown according to *hide* variable.
```{r}
"Also to be hidden according to 'hide' variable"
hist(rnorm(10))
```
```{r results='asis', echo=FALSE}
if (hide) {cat("-->")}
```
<!--
Never shown.
-->
## End
Always shown.
Just a caveat: in html output the hidden parts are kept as comments and can be seen just by viewing the source. On the other hand, PDF (LaTex) and Word outputs ignore html comments and the hidden parts aren't included in the knitted documents.
Therefore, when the hidden parts are supposed to be somehow confidential (e.g. exam solutions) PDF or Word output should be used instead of html.
For those looking for a solution when knitting to pdf through LaTex, the answer from #Pere won't work for you (because LaTex doesn't understand the <!--- --> pair as indicating a comment).
Below is one possible workaround:
---
output:
pdf_document
---
\newcommand{\ignore}[1]{}
```{r echo=FALSE}
include <- TRUE
```
```{r results='asis', echo=FALSE}
if(!include){cat("\\ignore{")}
```
Included bla bla
```{r results='asis', echo=FALSE}
if(!include){cat("}")}
```
```{r echo=FALSE}
include <- FALSE
```
```{r results='asis', echo=FALSE}
if(!include){cat("\\ignore{")}
```
NOT Included bla bla
```{r results='asis', echo=FALSE}
if(!include){cat("}")}
```

knitr plots, labels, and captions within one chunk - .Rmd files

Jallen produced a solution for producing knitr plots, labels, and captions within one chunk - for Rnw files.
knitr plots, labels, and captions within one chunk
This works nicely for .Rnw but I can't make it work for .Rmd, don't see what is going wrong...
---
output:
pdf_document:
fig_caption: yes
fig_crop: no
---
```{r startup,echo=FALSE,results='hide',message=FALSE,tidy=FALSE,warning=FALSE,fig.keep='all',comment=NA}
require(knitr)
require(ggplot2)
opts_knit$set(progress = F, verbose = F)
opts_chunk$set(comment=NA,
tidy=FALSE,
warning=FALSE,
message=FALSE,
echo=FALSE,
dpi=600,
fig.width=6.75, fig.height=4, # Default figure widths
dev=c("pdf",'tiff'),
dev.args=list(pdf=list(NULL),tiff=list(compression='lzw')),
error=FALSE)
```
```{r plotloop,results='asis'}
for(x in seq(1,20)){
x1<-data.frame(x=seq(1,10),y=seq(1,10))
plt<-ggplot(data=x1,aes(x,y))+geom_point()
figLabel=paste('Figure',x,sep='')
capt<-paste('Caption for fig.',x)
cat(knit(text=(paste("```{r ",figLabel,",fig.pos='h',fig.cap='",capt,"'}\nplt\n```",sep=''))))
cat('\\newpage')
plot.knit function in knitr plots, labels, and captions within one chunk can be modified to account for the syntax of markdown as opposed to latex. plot.knit.md becomes
plot.knit.md<-function(chunkLabel,#text for chunk label which is also used for figure file name
capt,#text for caption
plt,
...)
{
cat(knit(text=knit_expand(text="```{r, {{chunkLabel}},eval=TRUE,fig.cap='{{capt}}',echo=FALSE}\nplt\n```"),
quiet=TRUE))
}
This works in the following markdown doc.
---
title: "plot.knit.md demo"
author: "Joel Allen"
date: "04/23/2015"
output:
html_document: default
pdf_document:
fig_caption: yes
---
This is an R Markdown document to demonstrate the generation of self-contained code chunks in a markdown file. It is particularly useful for situations where multiple plots are generated in a single code chunk allowing for dynamic label and caption support.
This example draws on
http://stackoverflow.com/questions/21685885/knitr-plots-labels-and-captions-within-one-chunk
in response to
https://stackoverflow.com/questions/27443019/knitr-plots-labels-and-captions-within-one-chunk-rmd-files
Items to note:
#. output pdf_document fig_caption option must be set to yes
#. plot.knit has been modified to plot.knit.md to account for the different syntax needed.
```{r, echo=FALSE,results='asis'}
plot.knit.md<-function(chunkLabel,#text for chunk label which is also used for figure file name
capt,#text for caption
plt,
...)
{
cat(knit(text=knit_expand(text="```{r, {{chunkLabel}},eval=TRUE,fig.cap='{{capt}}',echo=FALSE}\nplt\n```"),
quiet=TRUE))
}
require(ggplot2)
cars.p<-ggplot(cars,aes(x=speed,y=dist))+
geom_point()
plot.knit.md(chunkLabel="carsPlot",capt="this is a caption for the cars plot",plt=cars.p)
```
One thing to figure out though is the attachment of labels...

Resources