将嵌套的 data.frame 转换为分层列表 [英] Convert nested data.frame to a hierarchical list

查看:35
本文介绍了将嵌套的 data.frame 转换为分层列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种巧妙的方法可以将嵌套的 data.frame 转换为分层列表?

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

我在下面使用 for 循环来完成它,但理想情况下有一个更简洁的解决方案,可以推广到任意数量的嵌套列.

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)

推荐答案

如果你对zy这两个名字不是很严格,也可以用[[1]][[2]],那么就可以直接做,

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)

如果你需要名字,那么

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))

这篇关于将嵌套的 data.frame 转换为分层列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆