4
votes

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
3

3 Answers

9
votes

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.

2
votes

Update

I found a better solution.

This works both in case of simple and complicated lists like the one I posted before (below)

l %>% map_dfr(~ .x %>% as_tibble(), .id = "name")

give us

# A tibble: 5 x 2
  name  value
  <chr> <dbl>
1 x        1.
2 x        2.
3 y        3.
4 y        4.
5 y        5.

==============================================

Original answer

From tidyverse:

l %>% 
  map(~ as_tibble(.x)) %>% 
  map2(names(.), ~ add_column(.x, Name = rep(.y, nrow(.x)))) %>% 
  bind_rows()

give us

# A tibble: 5 × 2
  value  Name
  <dbl> <chr>
1     1     x
2     2     x
3     3     y
4     4     y
5     5     y

The stack function from base R is great for simple lists as Jaap showed.

However, with more complicated lists like:

l <- list(
  a = list(num = 1:3, let_a = letters[1:3]),
  b = list(num = 101:103, let_b = letters[4:6]),
  c = list()
)

we get

stack(l)

values ind
1       1   a
2       2   a
3       3   b
4       a   b
5       b   a
6       c   a
7     101   b
8     102   b
9     103   a
10      d   a
11      e   b
12      f   b

which is wrong.

The tidyverse solution shown above works fine, keeping the data from different elements of the nested list separated:

# A tibble: 6 × 4
    num   let  Name  lett
  <int> <chr> <chr> <chr>
1     1     a     a  <NA>
2     2     b     a  <NA>
3     3     c     a  <NA>
4   101  <NA>     b     d
5   102  <NA>     b     e
6   103  <NA>     b     f
1
votes

We can use melt from reshape2

library(reshape2)
melt(l)
#   value L1
#1     1  x
#2     2  x
#3     3  y
#4     4  y
#5     5  y