Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert list to data frame while keeping list-element names

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

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   

To:

ID   Obs  
1    1  
1    2
2    1
2    2
2    3
3    1
like image 974
ego_ Avatar asked Sep 28 '12 11:09

ego_


2 Answers

Here is one way:

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

This gives:

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

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.

like image 68
Gavin Simpson Avatar answered Sep 19 '22 12:09

Gavin Simpson


Use reshape2 and melt which has a method melt.list

.list <- list(`1` = 1:2, `2` = 1:3, `3` = 1:2)
library(reshape2)
melt(.list)
##   value L1
## 1     1  1
## 2     2  1
## 3     1  2
## 4     2  2
## 5     3  2
## 6     1  3
## 7     2  3
like image 41
mnel Avatar answered Sep 19 '22 12:09

mnel