将列表转换为数据框,同时保留列表元素名称 [英] Convert list to data frame while keeping list-element names

查看:44
本文介绍了将列表转换为数据框,同时保留列表元素名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表,其中元素名称是ID标签,并且包含带有数字值的向量.它们的长度不相等!!

I have list where the elementnames are ID-tags and contains a vector with numeric values. These are of unequal(!) length.

我想将其转换为一个数据框,其中一列具有ID,另一列具有数值.例如:

I want to transform it to a data frame where I have the ID in one column and the numeric values in another column. E.g.:

$`1`  
[1] 1 2   
$`2`  
[1] 1 2 3 
$`3`  
[1] 1   

收件人:

ID   Obs  
1    1  
1    2
2    1
2    2
2    3
3    1

推荐答案

这是一种方法:

## your list
ll <- list("1" = 1:2, "2" = 1:3, "3" = 1:2)
## convert to data.frame
dl <- data.frame(ID = rep(names(ll), sapply(ll, length)),
                 Obs = unlist(ll))

这给出了:

> dl
   ID Obs
11  1   1
12  1   2
21  2   1
22  2   2
23  2   3
31  3   1
32  3   2

data.frame()调用中的第一行只是一些代码,用于将列表的names()重复所需的次数.第二行只是取消列出列表,将其转换为向量.

The first line in the data.frame() call is just some code to repeat the names() of the list the required number of times. The second line just unlists the list converting it into a vector.

这篇关于将列表转换为数据框,同时保留列表元素名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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