elliot
elliot

Reputation: 1944

Turn list of different length vectors into a `tibble`

I currently have a list of character vectors that are different lengths. Like this:

list(
  c('this','is','first'),
  c('this','is','second','it','longer'),
  c('this is a list','that is length 2')
)

I'd like to combine all the elements of each vector in the list into a single row in a tibble. Like this:

data_frame(column_1 =
             c('this is first',
               'this is second it longer',
               'this is a list that is length 2'))

I'd like to use base R or packages from the tidyverse if possible.

Upvotes: 0

Views: 709

Answers (1)

MrFlick
MrFlick

Reputation: 206243

You can use purrr and stringr

x <- list(
  c('this','is','first'),
  c('this','is','second','it','longer'),
  c('this is a list','that is length 2')
)

tibble(column1= map_chr(x, str_flatten, " "))

Note that str_flatten is new to stringr_1.3.0

This could also be easily done with base R (no tidyverse functions)

data.frame(column1 = sapply(x, paste, collapse= " "))

Upvotes: 3

Related Questions