平坦的嵌套列表并保留每个底层元素的所有父键
我需要将任意的< / strong>嵌套列表弄平到数据框架,并将键 /索引的路径保留在一个列中,同时将每个元素在底部级别提取到单个行。
考虑以下列表:
lst <- list(
animals = list(
lamas = c("brown", "white"),
primates = list(
humans = c("asia", "europe"),
apes = c("good", "fast", "angry")
)
),
objects = c("expensive", "cheap"),
plants = NULL
)
flatten_list(lst,deLimiter =“ _”)
的结果应该像这样:
data.frame(
path = c("animals_lamas", "animals_lamas", "animals_primates_humans", "animals_primates_humans", "animals_primates_apes", "animals_primates_apes", "animals_primates_apes", "objects", "objects", "plants"),
value = c("brown", "white", "asia", "europe", "good", "fast", "angry", "expensive", "cheap", NA)
)
我很惊讶我无法用Tidyr或Data.tables无法实现这一目标。我需要递归功能,还是为此提供一些开箱即用的解决方案?赞赏!
编辑: akrun 提供了原始数据的解决方案。我意识到,当元素在底部null
时,存在问题,从而使问题重新解决了。
edit2 我目前的解决方法是递归null
by na
在应用 akrun 解决方案,使用函数在这里提供的 [再次由Akrun;)]。
I need to flatten an arbitrarily nested list to a data frame and retain the path of keys / indices in one column, while extracting each element on the bottom level to an individual row.
Consider the following list:
lst <- list(
animals = list(
lamas = c("brown", "white"),
primates = list(
humans = c("asia", "europe"),
apes = c("good", "fast", "angry")
)
),
objects = c("expensive", "cheap"),
plants = NULL
)
The results of flatten_list(lst, delimiter="_")
should look like this:
data.frame(
path = c("animals_lamas", "animals_lamas", "animals_primates_humans", "animals_primates_humans", "animals_primates_apes", "animals_primates_apes", "animals_primates_apes", "objects", "objects", "plants"),
value = c("brown", "white", "asia", "europe", "good", "fast", "angry", "expensive", "cheap", NA)
)
I was surprised that I couldn't achieve this with tidyr or data.tables. Do I need a recursive function, or is there some out-of-the-box solution for this? Appreciated!
EDIT: The solution provided by akrun worked on the original data. I realized that there is a problem when an element is NULL
at the bottom level and hence rephrased the problem.
EDIT2 My current workaround is to recursively replace NULL
by NA
before applying akrun solution, using the function supplied here [again by akrun ;) ].
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一个可以基于
rrapply
的解决方案,可以处理null
:A solution that can deal with
NULL
, based onrrapply
:可以通过
Melt
in到数据。FRAME,然后unite
使用OP输出来检查
键列 -我们也可以使用
linist 和
stack
来自base r
It can be done by
melt
ing into a data.frame and thenunite
the key columns-checking with OP's output
We may also do this with
unlist
andstack
frombase R