Skip to content

Instantly share code, notes, and snippets.

@gadenbuie
Created April 14, 2023 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gadenbuie/e6368d29a1ce8f9b5cceafcf0ef97d8e to your computer and use it in GitHub Desktop.
Save gadenbuie/e6368d29a1ce8f9b5cceafcf0ef97d8e to your computer and use it in GitHub Desktop.

Reading a YAML chunk

Here’s a simple YAML chunk (with the label config):

default:
  user: "garrick"
  github: "gadenbuie"

And now I’ll read that data into an R object that I could use in my document.

config_yaml <- knitr::knit_code$get("config")
config <- yaml::yaml.load(config_yaml)
config
## $default
## $default$user
## [1] "garrick"
## 
## $default$github
## [1] "gadenbuie"
---
title: Reading a YAML chunk
output: github_document
---
Here's a simple YAML chunk (with the label `config`):
```{yaml config}
default:
user: "garrick"
github: "gadenbuie"
```
And now I'll read that data into an R object
that I could use in my document.
```{r}
config_yaml <- knitr::knit_code$get("config")
config <- yaml::yaml.load(config_yaml)
config
```
@cderv
Copy link

cderv commented Apr 14, 2023

Good trick !

You do have the warning about unknown engine

Dans get_engine(options$engine) :
  Unknown language engine 'yaml' (must be registered via knit_engines$set()).

So relying on a side effect behavior that we still fill knitr::knit_code with the content of chunk with unknown engine. Clever trick really.

I would have done this way using the cat() engine

---
title: Reading a YAML chunk
output: github_document
---

Using the `cat()` engine to write YAML to file, and `echo` the content

```{cat, engine.opts = c(file = (yaml_file <- tempfile(fileext = ".yml"))), lang = "yaml"}
default:
  user: "garrick"
  github: "gadenbuie"
```

The file created could then be read for further processing. 

```{r}
config <- yaml::read_yaml(yaml_file)
config
```

The easiest way though is probably to

  • Write an external YAML file
  • Using embed engine to show the content in the first chunk
  • Using R engine to read the external YAML for processing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment