使用unlist递归地简化列表

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

考虑这样的情况:

xml_list <- list(
  a = "7",
  b = list("8"),
  c = list(
    c.a = "7",
    c.b = list("8"), 
    c.c = list("9", "10"),
    c.d = c("11", "12", "13")),
  d = c("a", "b", "c"))

我正在寻找的方法是如何递归地简化这个结构,以便在长度为1的任何unlist上调用list。上面示例的预期结果如下所示:

list(
  a = "7",
  b = "8",
  c = list(
    c.a = "7",
    c.b = "8", 
    c.c = list("9", "10"),
    c.d = c("11", "12", "13")),
 d = c("a", "b", "c"))

我已经涉足rapply,但是明确地对list成员进行操作,这些成员本身并不是列表,所以写了以下内容:

library(magrittr)
clean_up_list <- function(xml_list){
  xml_list %>%
    lapply(
      function(x){
        if(is.list(x)){
          if(length(x) == 1){
            x %<>%
              unlist()
          } else {
            x %<>%
              clean_up_list()
          }
        }
        return(x)
      })
}

然而,我甚至无法测试Error: C stack usage 7969588 is too close to the limit(至少在我最终想要处理的列表中)。

深入挖掘(在仔细研究@Roland的回应之后),我提出了一个利用purrr-goodness的解决方案,反向迭代列表深度并且几乎可以做我想要的:

clean_up_list <- function(xml_list)
{
  list_depth <- xml_list %>%
    purrr::vec_depth()
  for(dl in rev(sequence(list_depth)))
  {
    xml_list %<>%
      purrr::modify_depth(
        .depth = dl,
        .ragged = TRUE,
        .f = function(x)
        {
          if(is.list(x) && length(x) == 1 && length(x[[1]]) == 1)
          {
            unlist(x, use.names = FALSE)
          } else {
            x
          }
        })
  }
  return(xml_list)
}

这似乎按照预期的方式工作,即使是我正在处理的深度列表。过去曾经是矢量的元素(如示例中的c.dd)现在被转换为lists,这违背了目的......任何进一步的见解?

r list purrr simplify
2个回答
1
投票

我不明白这个magrittr的东西,但是创建一个递归函数很容易:

foo <- function(L) lapply(L, function(x) {
  if (is.list(x) && length(x) > 1) return(foo(x))
  if (is.list(x) && length(x) == 1) x[[1]] else x
  })
foo(test_list)

#$`a`
# [1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S" "T" "U" "V" "W" "X" "Y" "Z"
#
#$b
#[1] "a"
#
#$c
#$c$`c.1`
#[1] "b"
#
#$c$c.2
# [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" "t" "u" "v" "w" "x" "y" "z"
#
#$c$c.3
#$c$c.3[[1]]
#[1] "c"
#
#$c$c.3[[2]]
#[1] "d"

如果这会引发有关C堆栈使用的错误,那么您将拥有深层嵌套的列表。那时你不能使用递归,这会使这成为一个具有挑战性的问题。如果可能的话,我会修改这个列表的创建。或者你可以尝试increase the C stack size


0
投票

ticketgithubpurrr存储库的帮助下,我解决了这个问题:使用当前开发人员版本的purrr(可通过remotes::install_github('tidyverse/purrr')安装),问题中的purrr-dpendent代码按预期工作,不再“listify”向量。因此,该代码应作为问题的答案,并在2018/19新年之后通过CRAN承载的包裹完全发挥作用。

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