I am trying to include as a subtitle in the yaml of a rmarkdown document an inline r code expression to get a part of the directory name.
So I tried this:
---
title: "Untitled"
subtitle: "`r getwd() |> str_split('/')|>pluck(1) |> pluck(7)`"
author: "Gandalf"
date: "`r Sys.Date()`"
output: html_document
---
The piece of code getwd() |> str_split('/')|>pluck(1) |> pluck(7)
works fine in a r chunk, but when in the yaml, it does not work when knitting, and this happens after the first pipe (if I only use subtitle: "`r getwd()`"
it works), e.g.this does not work:
---
title: "Untitled"
subtitle: "`r getwd() |> str_split('/')`"
author: "Gandalf"
date: "`r Sys.Date()`"
output: html_document
---
and I get a ‘halted execution’ in line 2 error message.
I tried the following which all failed:
subtitle: "`r getwd() |> stringr::str_split('/')`"
subtitle: "`r getwd() |> strsplit('/')`"
So I thought it was because of the pipe but the following actually works:
subtitle: "`r getwd() |> paste('hello')`"
The directory name looks like this: "D:/Oswaldo/Autoentrepreneur/Formateur_RStudio/Formation_Tidyverse/Sessions_clients/2024_06_24.Presentiel.Module_deb.CD_UM_fr/evaluations/satisfaction_beneficiaires"
So, what am I missing?
1
The following should work that avoids using the pipe operator and base R strsplit()
:
---
title: "Untitled"
subtitle: "`r strsplit(getwd(), '/')[[1]][7]`"
author: "Gandalf"
date: "`r Sys.Date()`"
output: html_document
---
When render tab in RStudio shows Execution halted
, switch from Issues to Output for some further hints.
For example your getwd() |> stringr::str_split('/')
and getwd() |> strsplit('/')
fail as those return lists:
But as long as your calls include package names and do not return something that confuses knitr
, you should be fine, i.e:
---
title: "Untitled"
author: "Gandalf"
subtitle: "`r getwd() |> stringr::str_split_i('/', 7)`"
date: "`r Sys.Date()`"
output: html_document
---
You also have an option to split YAML block and set subtitle
after you have loaded packages:
---
title: "Untitled"
author: "Gandalf"
date: "`r Sys.Date()`"
output: html_document
---
```{r setup, include=FALSE}
library(purrr)
library(stringr)
```
---
subtitle: "`r getwd() |> str_split('/') |> pluck(1) |> pluck(7)`"
---
2