考虑这样的情况:
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
。以上示例的预期结果如下:< / p>
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
,但是它明确地对{strong>未列出自己的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
-善良性,对列表深度进行反向迭代,并且 NEARLY 可以满足我的要求:
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)
}
即使对于我正在处理的曾经是向量的 BUT 元素的深度列表,此似乎也可以正常工作(示例中的c.d
和d
)现在转换为lists
,这违背了目标……还有任何进一步的见解吗?
答案 0 :(得分: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。
答案 1 :(得分:0)
借助ticket对github
的{{1}}存储库的帮助,我解决了这个问题:使用当前开发人员的purrr
版本(可通过purrr
安装),问题中的remotes::install_github('tidyverse/purrr')
-分隔符代码将按预期工作,并且不再“侦听”向量。因此,该代码应作为问题的答案,并在2018/19新年后通过purrr
承载的软件包完全起作用。