将数据框转换为深度嵌套的列表 [英] Converting data frame into deeply nested list
问题描述
我正在尝试创建whisker
软件包期望的数据结构,但似乎无法弄清楚
从我的数据框创建该结构.假设我有以下数据框:
I'm trying to create a data structure that the whisker
package expects, and I can't seem to figure out how
create that structure from my data frame. Let's say I have the following data frame:
library(dplyr)
existing_format <-
mtcars %>%
select(carb, gear, cyl) %>%
arrange(carb, gear, cyl) %>%
distinct()
...我想从existing_format
转到以下所需格式(仅显示desired_format
列表的前两个元素):
...I would like to go from existing_format
to the following desired format (only first two elements of desired_format
list are shown):
desired_format <- list(
list(
carb = "1",
gear = list(
list(gear = "3", cyl = list(list(cyl = "4"), list(cyl = "6"))),
list(gear = "4", cyl = list(list(cyl = "4")))
)
),
list(
carb = "2",
gear = list(
list(gear = "3", cyl = list(list(cyl = "8"))),
list(gear = "4", cyl = list(list(cyl = "4"))),
list(gear = "5", cyl = list(list(cyl = "4")))
)
)
)
我尝试过按carb
和gear
分组的方法,然后使用tidyr::nest()
创建嵌套的df,但是没有任何反应.某事告诉我whisker::iteratelist()
或whisker::rowSplit()
是前进的方向,但我无法弄清楚.
I've tried things like grouping by carb
and gear
, then using tidyr::nest()
to create a nested df, but nothing is doing. Something tells me that whisker::iteratelist()
or whisker::rowSplit()
is the way forward, but I can't figure it out.
谢谢, 克里斯
推荐答案
在这种情况下,也许比它需要的灵活得多,但是您可以进行递归拆分
Perhaps more flexible than it needs to be in this case, but you can do a recursive split
rsplit<-function(dd) {
col <- names(dd)[1]
dat <- dd[[1]]
xx <- lapply(unique(dat), function(x) {
z <- setNames(list(x), col)
if(ncol(dd)>1) {
z[[names(dd)[2]]] <- rsplit(dd[dat==x,-1, drop=FALSE])
}
z
})
xx
}
rsplit(existing_format)
这将拆分所有列,并使用列标题中的名称.
This will split on all the columns and use the names from the column headers.
这篇关于将数据框转换为深度嵌套的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!