Transforming Nested Lists in R for YAML config

99 views Asked by At

I have a config file for Mkdocs in Yaml that I'm trying to modify, and it requires a slightly strange nested list structure. After finding some code online that turned a dataframe into a standard nested list structure, I'm trying to modify it into the exact list structure I need.

nested_lists_current = list(
  census = list(
    acs = list(logrecno = 1, moe = 3,seq = 5),
    geo = list(fileid = 2, geoid = 4,macc = 6)
  )
)
nested_lists_ideal = list(
  list(
    census = list(
      list(
        acs = list(
          list(logrecno = 1), 
          list(moe = 3),
          list(seq = 5)
        )
      ),
      list(
        geo = list(
          list(fileid = 2), 
          list(geoid = 4),
          list(macc = 6)
        )
      )
    )
  )
)

Currently, when using the yaml package, nested_lists_current parses into:

  census:
    acs:
      logrecno: 1.0
      moe: 3.0
      seq: 5.0
    geo:
      fileid: 2.0
      geoid: 4.0
      macc: 6.0

and I need it to parse into:

- census:
  - acs:
    - logrecno: 1.0
    - moe: 3.0
    - seq: 5.0
  - geo:
    - fileid: 2.0
    - geoid: 4.0
    - macc: 6.0

Does anyone know how to transform current into ideal, in a way that is extensible to more items at each level, but not necessarily a higher level of nesting? Thanks.

I've tried using map_depth and lapply, along the lines of map_depth(0,~list(.x)), but it resulted in a structure that would encapsulate both acs and geo into the same list.

1

There are 1 answers

0
MrFlick On

You can write a helper function to do the transformation

transform_list <- function(x) {
  if (is.list(x)) {
    unname(Map(function(x, name) setNames(list(transform_list(x)), name), x, names(x)))
  } else {
    x
  }
}

Then if you run

cat(yaml::as.yaml(transform_list(nested_lists_current)))

You get

- census:
  - acs:
    - logrecno: 1.0
    - moe: 3.0
    - seq: 5.0
  - geo:
    - fileid: 2.0
    - geoid: 4.0
    - macc: 6.0

Basically the helper function recursively finds all the lists and turns them into nested lists.