Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove empty elements from yaml in R

Tags:

r

yaml

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?

like image 911
Quinten Avatar asked Jun 24 '26 20:06

Quinten


2 Answers

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
like image 105
SamR Avatar answered Jun 26 '26 10:06

SamR


With purrr we could also opt for modify_tree() + compact():

library(yaml)
library(purrr)

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

modify_tree(z, post = compact) |> 
  as.yaml() |> 
  cat()
#> tree:
#>   format: newick
#> tracks:
#> - class: colorstrip

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

like image 26
margusl Avatar answered Jun 26 '26 09:06

margusl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!