Convert nested data.frame to a hierarchical list

好久不见. 提交于 2021-01-29 20:34:36

问题


Is there a neat way to convert a nested data.frame to a hierarchical list?

I do it below with a for loop, but ideally there is a neater solution that generalizes to an arbitrary number of nested columns.

nested_df <- expand.grid(V1 = c('a','b','c'),
                         V2 = c('z','y'))%>%
    group_by_all()%>%
    do(x=runif(10))%>%
    ungroup

nested_ls <- list()
for(v1 in unique(nested_df$V1)){
    for(v2 in unique(nested_df$V2)){
        nested_ls[[v1]][[v2]] <- nested_df%>%
            filter(V1==v1 & V2==v2)%>%
            pull(x)%>%
            unlist
    }
}

str(nested_ls)

回答1:


If you are not very strict with the names z and y, and can also work with [[1]] and [[2]], then you can directly do,

split(nested_df$x, nested_df$V1)

If you need the names, then

lapply(split(nested_df, nested_df$V1), function(i)split(i$x, i$V2))

#Or as @Frank mentions in comments, we can use setNames
lapply(split(nested_df, nested_df$V1), function(i) setNames(i$x, i$V2))


来源:https://stackoverflow.com/questions/55264739/convert-nested-data-frame-to-a-hierarchical-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!