简体   繁体   English

将不同长度向量的列表变成小标题

[英]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 . 我想在列表中的每个向量的所有元素组合成一个单一的行中的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. 我想尽可能使用base R或tidyverse软件包。

You can use purrr and stringr 您可以使用purrrstringr

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 请注意, str_flattenstr_flatten的新stringr_1.3.0

This could also be easily done with base R (no tidyverse functions) 使用基数R(没有tidyverse函数)也可以轻松完成此操作

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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