首页 > 解决方案 > 将列表列表转换为长格式的数据框

问题描述

我有一个列表列表

list_of_lists <- list(a = 1, 
                      b = 2:3,
                      c = 4:6)

我想将其转换为两列的“长格式”数据框。就像是

> rbind(data.frame(KEY = names(list_of_lists)[1], VALUE = list_of_lists[[1]]),
        data.frame(KEY = names(list_of_lists)[2], VALUE = list_of_lists[[2]]),
        data.frame(KEY = names(list_of_lists)[3], VALUE = list_of_lists[[3]]))

  KEY VALUE
1   a     1
2   b     2
3   b     3
4   c     4
5   c     5
6   c     6

我会知道如何用循环解决这个问题,但必须有更直接的方法来做到这一点。我试图重新调整这个问题的用途,但对裁缝对我的问题的答案缺乏足够的理解。
奖金,如果有一个dplyr-style 解决方案。

标签: rlistdataframedplyrdata-conversion

解决方案


推荐阅读