Search code examples
rlistdataframer-faq

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

Solution

  • 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.