将列表中的字符串元素合并到R中的一个变量中

将列表中的字符串元素合并到R中的一个变量中,r,R,我有一个数据帧(df),其中有一个变量,它是一个包含字符串向量的列表(mylist) 如何将mylist的元素组合到每行的单个变量中?我希望我的数据如下所示: id mylist 1 "a b c" 2 "d e f g h" 3 "x y z k" 一个dplyr选项可以是: df %>% rowwise() %>% mutate(mylist = Reduce(paste, mylist)) id

我有一个数据帧(df),其中有一个变量,它是一个包含字符串向量的列表(mylist)

如何将mylist的元素组合到每行的单个变量中?我希望我的数据如下所示:

id mylist
1  "a b c"
2  "d e f g h"
3  "x y z k"

一个
dplyr
选项可以是:

df %>%
 rowwise() %>%
 mutate(mylist = Reduce(paste, mylist))

     id mylist   
  <int> <chr>    
1     1 a b c    
2     2 d e f g h
3     3 x y z k  
df%>%
行()
mutate(mylist=Reduce(粘贴,mylist))
id mylist
1 a b c
2 2 d e f g h
3xyzk

基本R选项是使用
sapply()
paste()
折叠列表元素:


一个选项是
unest
并通过
粘贴

library(dplyr)
library(tidyr)
library(stringr)
df %>%
    # // expand the dataset by unnesting the column
    unnest(c(mylist)) %>%
    # // grouped by id
    group_by(id) %>% 
    # // paste the elements of mylist to a single string
    summarise(mylist = str_c(mylist, collapse=' '))
# A tibble: 3 x 2
#    id mylist   
#  <int> <chr>    
#1     1 a b c    
#2     2 d e f g h
#3     3 x y z k  
库(dplyr)
图书馆(tidyr)
图书馆(stringr)
df%>%
#//通过取消对列的测试来扩展数据集
unnest(c(mylist))%>%
#//按id分组
分组依据(id)%>%
#//将mylist的元素粘贴到单个字符串
总结(mylist=str_c(mylist,collapse='')
#一个tibble:3x2
#id mylist
#       
#1 a b c
#2 2 d e f g h
#3xyzk
df$mylist <- sapply(mylist, paste, collapse = " ")
df

# A tibble: 3 x 2
     id mylist   
  <int> <chr>    
1     1 a b c    
2     2 d e f g h
3     3 x y z k 
library(purrr)
library(dplyr) 

df %>%
  mutate(mylist = map_chr(mylist, paste, collapse = " "))
library(dplyr)
library(tidyr)
library(stringr)
df %>%
    # // expand the dataset by unnesting the column
    unnest(c(mylist)) %>%
    # // grouped by id
    group_by(id) %>% 
    # // paste the elements of mylist to a single string
    summarise(mylist = str_c(mylist, collapse=' '))
# A tibble: 3 x 2
#    id mylist   
#  <int> <chr>    
#1     1 a b c    
#2     2 d e f g h
#3     3 x y z k