Search code examples
rlistpurrrtibble

List into tibble using list names as values in one column


I would like to transform a list like this:

l <- list(x = c(1, 2), y = c(3, 4, 5))

into a tibble like this:

 Name  Value 
 x      1
 x      2
 y      3
 y      4
 y      5

Solution

  • I think nothing will be easier than using the stack-function from base R:

    df <- stack(l)
    

    gives you a dataframe back:

    > df
      values ind
    1      1   x
    2      2   x
    3      3   y
    4      4   y
    5      5   y
    

    Because you asked for tibble as output, you can do as_tibble(df) (from the tibble-package) to get that.

    Or more directly: df <- as_tibble(stack(l)).


    Another pure base R method:

    df <- data.frame(ind = rep(names(l), lengths(l)),
                     value = unlist(l),
                     row.names = NULL)
    

    which gives a similar result:

    > df
      ind value
    1   x     1
    2   x     2
    3   y     3
    4   y     4
    5   y     5
    

    The row.names = NULL isn't necessarily needed but gives rownumbers as rownames.