Inside-chunk Quarto codes (#|) not working properly - pdf

None of the inside-chunk Quarto codes (#|) are working properly. I have a document with the following header.
title: "Title"
subtitle: "Subtitle"
author:
- "Author 1"
- "Author 2"
date: "November 8, 2022"
date-format: long
format:
html:
code-fold: true
html-math-method: katex
pdf:
cap-location: top
fig-cap-location: top
tab-cap-location: top
papersize: "a4paper"
geometry:
- top=20mm
- left=25mm
include-in-header:
text: |
\addtokomafont{disposition}{\rmfamily}
docx: default
```
With several code chunks inside it.
```{r}
#| label: #fig-atrip-hist
#| echo: false
#| error: false
#| fig-cap: "atrip Histogram and Density Plot"
#| fig-width: 2
#| fig-height: 3
ggplot(data=df.scaled, aes(atrip))+
geom_histogram(aes(y = ..density..))+
geom_density(color = "dark grey", linetype="dashed", fill = "#89f0f4", alpha = 0.6)+
theme_custom()
```
When I render the document to PDF, all codes are printed. To avoid that, I have to put the code inside the brackets, as if the document was a RMD.
{r echo=FALSE, message=FALSE, warning=FALSE}
In addition, the Figure captions are not printed in Quarto. They are only printed if I put the caption inside the brackets.
{r fig-cap: "atrip Histogram and Density Plot", echo=FALSE, message=FALSE, warning=FALSE}
My document is saved as a Quarto documento. I created it as a Quarto document. It has a .qmd extension. But it behaves as a RMD document.

Related

LaTex fails to compile PDF

Since yesterday, I get a confusing error, when trying to knit my Markdown files to PDF. I get this warning:
This is pdfTeX, Version 3.141592653-2.6-1.40.24 (TeX Live 2022) (preloaded format=pdflatex)
restricted \write18 enabled.
entering extended mode
I was unable to find any missing LaTeX packages from the error log Chapter-5-1.log.
! Extra }, or forgotten \endgroup.
\endwraptable ...kip \egroup \box \z# \fi \egroup
\WF#floatstyhook \def \wid...
l.156 \end{wraptable}
Fehler: LaTeX failed to compile Chapter-5-1.tex. See https://yihui.org/tinytex/r/#debugging for debugging tips. See Chapter-5-1.log for more info.
Ausführung angehalten
The problem seems to be the kable tables, which have been knit in prior tries just nicely. In the error log, this is printed:
Overfull \hbox (165.80571pt too wide) in paragraph at lines 142--158
[][]
[]
! Extra }, or forgotten \endgroup.
\endwraptable ...kip \egroup \box \z# \fi \egroup
\WF#floatstyhook \def \wid...
l.158 \end{wraptable}
A friend of mine tried to compile the tex file directly to PDF, but got the same error. We where not able to find a missing } or any other error in the coding. All tables and code is running without error in the markdown preview.
I get the same error, when I try to knit a document with a dummy table, so I hope that works as a reproducible example.
---
title: "Chapter 5"
author: "Moiken Hinrichs"
date: "`r format(Sys.time(), '%d.%m.%Y')`"
header-includes:
- \usepackage{caption}
- \usepackage{float}
- \captionsetup[figure]{font=footnotesize}
- \usepackage{subfig}
- \usepackage{flafter}
- \usepackage{footmisc}
output:
bookdown::pdf_document2:
extra_dependencies: ["flafter"]
number_sections: true
toc: false
latex_engine: xelatex
classoption: twoside
keep_tex: true
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(knitr)
library(kableExtra)
library(dplyr, quietly=T)
library(tidyr)
```
```{r prox}
column1 <- c("Bert", "Angela", "Nico", "Pam", "Max")
column2 <- c(33, 54, 85, 96, 57)
prox <- data.frame(column1, column2)
prox[nrow(prox)+1, ] <- c('Total', sum(prox$column2))
kable(prox, booktabs = T, linesep = "",
col.names = c("Name", "Count"),
caption = "Number of items") %>%
kable_styling(latex_options = "striped", position = "float_right") %>%
row_spec(5, hline_after = T) %>%
row_spec(6, bold = T)
```
R studio and tinytex are updated. I tried all the debugging tips and uninstalled and installed tinytex new. The same error is also happening when I try to knit on another computer. I also tried to change from xelatex to pdflatex but the error was the same.
The wrapfig package does not particular like zero width wrapfigure or -table environments with captions. Unfortunately that's the width rmarkdown seems to use by default.
The package documentation has the following to say about the topic:
[...] However, if you specify a width of zero (0pt), the actual width of the figure will determine the wrapping width. A following \caption should have the same width as the figure, but it might fail badly; it is safer to specify a width when you use a caption.
You can avoid the problem by choosing a suitable width:
---
title: "Chapter 5"
author: "Moiken Hinrichs"
date: "`r format(Sys.time(), '%d.%m.%Y')`"
header-includes:
- \usepackage{caption}
- \usepackage{float}
- \captionsetup[figure]{font=footnotesize}
- \usepackage{subfig}
- \usepackage{flafter}
- \usepackage{footmisc}
- \usepackage{lipsum}
output:
bookdown::pdf_document2:
extra_dependencies: ["flafter"]
number_sections: true
toc: false
latex_engine: xelatex
classoption: twoside
keep_tex: true
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(knitr)
library(kableExtra)
library(dplyr, quietly=T)
library(tidyr)
```
```{r prox}
column1 <- c("Bert", "Angela", "Nico", "Pam", "Max")
column2 <- c(33, 54, 85, 96, 57)
prox <- data.frame(column1, column2)
prox[nrow(prox)+1, ] <- c('Total', sum(prox$column2))
kable(prox, booktabs = T, linesep = "",
col.names = c("Name", "Count"),
caption = "Number of items") %>%
kable_styling(latex_options = "striped", position = "float_right", wraptable_width = "3cm") %>%
row_spec(5, hline_after = T) %>%
row_spec(6, bold = T)
```
\lipsum

Iterating to create tabs with gt in quarto

Something that is very handy is to iterate through a variable and then dynamically create tabs based on values of that variable (here homeworld). This works well with the results: asis chunk option. I can make that work but there is some strange interaction with the {gt} package whereby I can only make gt work with purrr::walk if I use gt::as_raw_html. However if I just produce a single table outside of purrr::walk I don't need gt::as_raw_html. Here is the error message I get {gt} does not work:
Error running filter
/Applications/quarto/share/filters/quarto-pre/quarto-pre.lua:
...lications/quarto/share/filters/quarto-pre/quarto-pre.lua:2410:
attempt to concatenate a nil value (local 'v') stack traceback:
...lications/quarto/share/filters/quarto-pre/quarto-pre.lua:2417: in
function
<...lications/quarto/share/filters/quarto-pre/quarto-pre.lua:2415>
Here is the quarto (quarto version 1.1.175) code to reproduce:
---
title: "Untitled"
format: html
execute:
warning: false
---
```{r r-pkgs}
library(dplyr)
library(glue)
library(gt)
library(purrr)
## just to simplify
starwars <- starwars %>%
filter(!is.na(sex))
```
# Does work
::: {.panel-tabset}
```{r}
#| results: asis
walk(
unique(starwars$sex), \(hw) {
cat(glue("## {hw} \n\n"))
starwars %>%
filter(sex == hw) %>%
count(homeworld) %>%
head() %>%
gt() %>%
as_raw_html() %>%
print()
cat("\n\n")
}
)
```
:::
# Does not work
::: {.panel-tabset}
```{r}
#| results: asis
#| eval: false
walk(
unique(starwars$sex), \(hw) {
cat(glue("## {hw} \n\n"))
starwars %>%
filter(sex == hw) %>%
count(homeworld) %>%
head() %>%
gt() %>%
print()
cat("\n\n")
}
)
```
:::
## single does work
```{r}
#| results: asis
starwars %>%
count(homeworld) %>%
head() %>%
gt()
```
Posting back answer from the duplicate issue in quarto-dev/quarto-cli#2370
About the issue
The behavior you see has to do with the print method used, and the iteration with walk()
When you use print() after gt() or after gt() %>% as_raw_html() it will not have the same effect, as the print method used will not be the same. In the context of knitr, this matters.
Using as_raw_html() makes sense to include table as raw HTML in such document, and it probably will have the same result as when gt object are printing in knitting to HTML table (though the use of htmltools). When you use gt() %>% print(), it will not use the correct printing method that is used when just gt() is in a chunk (the knit_print() method more on that here for advanced understanding.
More on how to create content dynamically with knitr
Let me add some context about knitr and dynamically created content.
Iterating to dynamically create content in knitr require to use the correct print method (usually knit_print()), and it is better to iterate on child content with knitr::knit_child() function that will correctly handle the printed output specific to sewing result in the document. We have some resource about that in R Markdown Cookbook that would apply to Quarto as well.
About knit_child() : https://bookdown.org/yihui/rmarkdown-cookbook/child-document.html
About knit_expand() also : https://bookdown.org/yihui/rmarkdown-cookbook/knit-expand.html
As an example, this is how we recommend to dynamically create content when using knitr content so that R code result is correctly mixed with other content, specifically when the content to dynamically create is a mix of raw markdown, and R code results.
---
title: "Untitled"
format: html
execute:
warning: false
keep-md: true
---
```{r r-pkgs}
library(dplyr)
library(glue)
library(gt)
library(purrr)
## just to simplify
starwars <- starwars %>%
filter(!is.na(sex))
```
# Tables
::: {.panel-tabset}
```{r}
#| output: asis
res <- purrr::map_chr(unique(starwars$sex), \(hw) {
knitr::knit_child(text = c(
"## `r hw`",
"",
"```{r}",
"#| echo: false",
"starwars %>%",
" filter(sex == hw) %>%",
" count(homeworld) %>%",
" head() %>%",
" gt()",
"```",
"",
""
), envir = environment(), quiet = TRUE)
})
cat(res, sep = '\n')
```
:::
You could also put the child content in a separate file for easier writing as in the Cookbook, by writing what you would need as document for one value you are iterating
## `r hw`
```{r}
#| echo: false
starwars %>%
filter(sex == hw) %>%
count(homeworld) %>%
head() %>%
gt()
```
This is the safest way to mix markdown content (like ##) with R code output ( like Tables or Htmlwidgets) which are content you can't easily just cat() into the file.
See more in the issue

How can I modify the color of cross-referencing in the R markdown generated pdf document?

---
title: "Annual Report"
author: "Xyz"
date: "`r format(Sys.time(),'%d %B, %Y')`"
output:
bookdown::pdf_document2:
extra_dependencies: ["float"]
number_sections: false
toc: false
linkcolor: blue
---
```{r, echo = FALSE}
library(ggplot2)
data(mtcars)
names(mtcars)
```
### Heading 1
```{r figure-1,echo=FALSE, fig.cap = "Sample Graph 1"}
ggplot(mtcars,aes(x=mpg,y=hp))+
geom_point()+
theme_classic()
```
To see another graph, please see figure \textcolor{blue}{\#ref(fig:figure-2)}
\newpage
### Heading 2
```{r figure-2,echo=FALSE, fig.cap = "Sample Graph 2"}
ggplot(mtcars,aes(x=mpg,y=carb))+
geom_point()+
theme_classic()
```
To see another graph, please see figure \#ref(fig:figure-1)
After execution, I found the following in knitted pdf document before Heading 2.
To see another graph, please see figure reffig:figure-2
reffig:figure in the code is not cross-referenced as well. What I want is that my document should show the following line in the pdf document:
To see another graph, please see figure 2
"2" in the above statement should be hyperlinked and its color should be blue, enabling the reader to jump to figure 2 if user clicks on "2".
Adding urlcolor:blue to your yaml should work.
---
title: "Annual Report"
author: "Xyz"
date: "`r format(Sys.time(),'%d %B, %Y')`"
output:
bookdown::pdf_document2:
extra_dependencies: ["float"]
number_sections: false
toc: false
linkcolor: blue
urlcolor: blue
---
Original answer found here: R markdown link is not formatted blue when knitted to pdf

kable unable to output unicode character in pdf_book (bookdown)

I am trying to use the checkmark unicode character (\u2713) in a table rendered by kable in a bookdown project. A MWE consists in the following 2 files (index.Rmd, preamble.tex) part of the generated minimal bookdown project.
index.Rmd
---
title: "A Minimal Book Example"
subtitle: "subtitle"
lang: fr
author: "Yihui Xie"
date: "`r Sys.Date()`"
site: bookdown::bookdown_site
documentclass: book
mainfont: Arial
mathfont: Arial
bibliography: [book.bib, packages.bib]
biblio-style: apalike
link-citations: yes
subparagraph: yes
description: "This is a minimal example of using the bookdown package to write a book. The output format for this example is bookdown::gitbook."
---
```{r setup, include=FALSE}
# Set locale to french for month and day names (calendar plots)
Sys.setlocale(locale = 'French')
# Load all needed libraries
if(!require('pacman'))install.packages('pacman')
pacman::p_load(kableExtra)
```
(ref:O3) O~3~
# Prerequisites
✓
```{r stations-polluants, echo=FALSE}
stations_polluants_table <- data.frame(
stations = c("41B001", "41B004", "41B011", "41MEU1", "41N043", "41R001", "41R002", "41R012", "41WOL1", "Total / polluant"),
O3 = c("", rep("✓", 5), "", rep("\u2713", 2), "7")
)
kable(stations_polluants_table, col.names = c("Station", "(ref:O3)"), booktabs = T, align = "c", caption = "Caption text") %>%
row_spec(0, bold = T) %>%
row_spec(10, bold = T) %>%
collapse_rows(columns = 1, latex_hline = "major", valign = "top")
```
```{r include=FALSE}
# automatically create a bib database for R packages
knitr::write_bib(c(
.packages(), 'bookdown', 'knitr', 'rmarkdown'
), 'packages.bib')
```
preamble.tex
\usepackage{booktabs}
\newfontfamily{\unicodefont}{Arial Unicode MS}
\usepackage{newunicodechar}
\newunicodechar{✓}{{\unicodefont{✓}}}
By compiling in PDF with rmarkdown::render_site(output_format = 'bookdown::pdf_book', encoding = 'UTF-8') one can notice that ✓ is correctly rendered in the text, while it is replaced by <U+2713> in the generated table. I also tried to use \u2713 in the table without more success.
What am I doing wrong ? Please note that, even if the prefered output is PDF, I would also like to compile as gitbook (so Rmd files need to stay independent from the output format).
Many thanks.
After having a moment of clarity, the solution simply lies in using text references in bookdown, i.e. (ref:check) ✓ and use the reference within the table.
index.Rmd
```{r setup, include=FALSE}
# Set locale to french for month and day names (calendar plots)
Sys.setlocale(locale = 'French')
# Load all needed libraries
if(!require('pacman'))install.packages('pacman')
pacman::p_load(kableExtra)
```
(ref:O3) O~3~
# Prerequisites
✓
(ref:check) ✓
```{r stations-polluants, echo=FALSE}
stations_polluants_table <- data.frame(
stations = c("41B001", "41B004", "41B011", "41MEU1", "41N043", "41R001", "41R002", "41R012", "41WOL1", "Total / polluant"),
O3 = c("", rep("(ref:check)", 5), "", rep("(ref:check)", 2), "7")
)
kable(stations_polluants_table, col.names = c("Station", "(ref:O3)"), booktabs = T, align = "c", caption = "Caption text") %>%
row_spec(0, bold = T) %>%
row_spec(10, bold = T) %>%
collapse_rows(columns = 1, latex_hline = "major", valign = "top")
```
```{r include=FALSE}
# automatically create a bib database for R packages
knitr::write_bib(c(
.packages(), 'bookdown', 'knitr', 'rmarkdown'
), 'packages.bib')
```

Graph-ET x-axis labels

I drew a bar diagram for my benchmarks in Graph-ET on Pharo. Does anybody
know how to add the labels to x-axis? I want to write the name of the benchmark under the each of bars.
Open a workspace, and type the following:
| chart |
chart := GETDiagramBuilder new.
chart verticalBarDiagram
models: ($a to: $z);
y: #asInteger;
regularAxis;
height: 200.
chart open.
"We use the same model elements"
($a to: $z) do: [ :value |
| bar label |
"We define a label, and add it to the view"
label := ROLabel elementOn: value asString.
chart rawView add: label.
"We get the bar, the gray element that grows up"
bar := chart rawView elementFromModel: value.
"Move the label below its corresponding bar"
ROConstraint move: label below: bar ].
"Inserting high level labels"
chart rawView add: ((ROLabel red elementOn: 'Chart about my life') translateBy: 200 # 0).
chart rawView add: ((ROLabel elementOn: 'Happiness') translateBy: -30 # -40).
chart rawView add: ((ROLabel elementOn: 'Passing days') translateBy: 650 # 210)
In GraphET2 (which uses Roassal2) building charts like the one you wanted is way easier!
| chart |
chart := GET2Bar data: ($a to: $z).
chart
y: #asInteger;
title: 'Chart about my life';
titleColor: Color red.
chart yAxis title: 'Happiness'.
chart xAxis addModelLabels:[:v | |s| s:= v asString. s,s,s,s. ];
verticalLabelsInverted;
title: 'Passing days'.
chart open.
Check it out here!
I hope it helps :)