将 R 中的嵌套列表转换为 YAML 配置

问题描述 投票:0回答:1

我在 Yaml 中有一个 Mkdocs 的配置文件,我正在尝试修改它,它需要一个稍微奇怪的嵌套列表结构。在网上找到一些将数据帧转换为标准嵌套列表结构的代码后,我尝试将其修改为我需要的确切列表结构。

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)
        )
      )
    )
  )
)

目前,使用yaml包时,nested_lists_current解析为:

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

我需要它解析为:

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

有谁知道如何将当前转化为理想,以一种可以扩展到每个级别的更多项目的方式,但不一定是更高级别的嵌套?谢谢。

我尝试过使用map_depth和lapply,沿着

map_depth(0,~list(.x))
的路线,但它产生了一个将acs和geo封装到同一个列表中的结构。

r dplyr yaml purrr mkdocs
1个回答
1
投票

您可以编写一个辅助函数来进行转换

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

然后如果你跑

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

你得到了

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

基本上,辅助函数会递归地查找所有列表并将它们转换为嵌套列表。

© www.soinside.com 2019 - 2024. All rights reserved.