Citizen
Citizen

Reputation: 121

convert lists of vectors in just one tibble data frame

I have two lists. Each of them with many vectors (around 500) of different lengths and I would like to get a tibble data frame with three columns.

My reproducible example is the following:

> a
[[1]]
[1] 1 3 6

[[2]]
[1] 5 4
> b
[[1]]
[1] 3 4

[[2]]
[1] 5 6 7

I would like to get the following tibble data frame:

name index value
a    1     1
a    1     3
a    1     6
a    2     5
a    2     4
b    1     3
b    1     4
b    2     5
b    2     6
b    2     7

I would be grateful if someone could help me with this issue

Upvotes: 0

Views: 1702

Answers (2)

akrun
akrun

Reputation: 886948

Here is one option with tidyverse

library(tidyverse)
list(a= a, b = b) %>%
      map_df(enframe, name = "index", .id = 'name') %>% 
      unnest
# A tibble: 10 x 3
#   name  index value
#   <chr> <int> <dbl>
# 1 a     1         1
# 2 a     1         3
# 3 a     1         6
# 4 a     2         5
# 5 a     2         4
# 6 b     1         3
# 7 b     1         4
# 8 b     2         5
# 9 b     2         6
#10 b     2         7

data

a <- list(c(1, 3, 6), c(5, 4))
b <- list(c(3, 4), c(5, 6, 7))

Upvotes: 2

Onyambu
Onyambu

Reputation: 79198

using Base R:

transform(stack(c(a=a,b=b)),name=substr(ind,1,1),ind=substr(ind,2,2))
   values ind name
1       1   1    a
2       2   1    a
3       3   1    a
4       5   2    a
5       6   2    a
6       3   1    b
7       4   1    b
8       5   2    b
9       6   2    b
10      7   2    b

using tidyverse:

library(tidyverse)
list(a=a,b=b)%>%map(~stack(setNames(.x,1:length(.x))))%>%bind_rows(.id = "name")
   name values ind
1     a      1   1
2     a      2   1
3     a      3   1
4     a      5   2
5     a      6   2
6     b      3   1
7     b      4   1
8     b      5   2
9     b      6   2
10    b      7   2

Upvotes: 1

Related Questions