简体   繁体   中英

In R: How to coerce a list of vectors with unequal length to a dataframe using tidyverse?

Suppose you have the following list in R:

list_test <- list(c(2,4,5, 6), c(1,2,3), c(7,8))

What I am looking for is a dataframe of the following form:

value list_index
  2      1
  4      1
  5      1
  6      1
  1      2
  2      2
  3      2
  7      3
  8      3

I tried to find a solution with the tidyverse but either lost the the list_index/name or had problems with the unequal length of the vectors.

You can give name to the list and then use stack in base R.

names(list_test) <- seq_along(list_test)
stack(list_test)

#  values ind
#1      2   1
#2      4   1
#3      5   1
#4      6   1
#5      1   2
#6      2   2
#7      3   2
#8      7   3
#9      8   3

If interested in a tidyverse solution we can use enframe with unnest .

tibble::enframe(list_test) %>% tidyr::unnest(value)

Or imap_dfr from purrr .

purrr::imap_dfr(list_test, ~tibble::tibble(value = .x, list_index = .y))

Another option could be:

map_dfr(list_test, ~ enframe(.) %>%
         select(-name), .id = "name")

  name  value
  <chr> <dbl>
1 1         2
2 1         4
3 1         5
4 1         6
5 2         1
6 2         2
7 2         3
8 3         7
9 3         8

Or if you don't mind to have a column also with vector indexes:

map_dfr(list_test, enframe, .id = "name_list")

  name_list  name value
  <chr>     <int> <dbl>
1 1             1     2
2 1             2     4
3 1             3     5
4 1             4     6
5 2             1     1
6 2             2     2
7 2             3     3
8 3             1     7
9 3             2     8

In base R , we can use lengths to replicate the sequence and unlist the list elements into a two column 'data.frame'

data.frame(value = unlist(list_test), 
     list_index = rep(seq_along(list_test), lengths(list_test)))
#  value list_index
#1     2          1
#2     4          1
#3     5          1
#4     6          1
#5     1          2
#6     2          2
#7     3          2
#8     7          3
#9     8          3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM