ryaml

Remove empty elements from yaml in R


I would like to remove some empty elements from a YAML in R. Empty elements could be shown as [] in a yaml. I found the ymlthis package with the yml_discard(~is_yml_blank(.x)) option. This should remove the empty elements from the yaml but this doesn't work. Here is a reproducible example:

library(yaml)
library(ymlthis)
z <- yaml.load(
  "tree:
  format: newick
tracks:
  - class: colorstrip
    rel_height: []
    title: ")

y <- as.yaml(z)

y |>
  yml_discard(~is_yml_blank(.x))
#> ---
#> tree:
#>   format: newick
#> tracks:
#> - class: colorstrip
#>   rel_height: []
#>   title: null
#> ---

Created on 2024-11-08 with reprex v2.1.1

As you can see it doesn't remove the empty values. My expected output should look like this:

#> ---
#> tree:
#>   format: newick
#> tracks:
#> - class: colorstrip
#> ---

The expected output shows that the elements with no value should be removed. So I was wondering if anyone knows how to remove empty elements in a YAML file in R?


Solution

  • It seems easier to work with z, which is a tree (or in R terms an arbitrary depth nested list), than y, which is a string (or character vector of length one). For example, use rrapply::rapply() to prune any empty elements of z, then convert to a yaml string:

    rrapply::rrapply(z, \(x) !is.null(x), how = "prune") |>
        as.yaml()
    

    This returns:

    tree:
      format: newick
    tracks:
    - class: colorstrip