简体   繁体   中英

Use purrr to collapse a vector of characters into a string of character

I want to use purrr to concatenate a character field in to tibble into a string.

d <- tibble(x = letters, y = c(rep(1,13), rep(2,13)) )
d
# output desired
tibble(y      =  c(1,2), 
       result =  c(stringr::str_c(letters[1:13],collapse = ","), stringr::str_c(letters[14:26], collapse = ",")))

Not sure what purrr function you want to use; but you can do the following in dplyr

library(dplyr)
d %>% group_by(y) %>% summarise(result = paste(x, collapse = ","))
## A tibble: 2 x 2
#      y result
#  <dbl> <chr>
#1     1 a,b,c,d,e,f,g,h,i,j,k,l,m
#2     2 n,o,p,q,r,s,t,u,v,w,x,y,z

Or using nest (in response to your comment)

d %>% group_by(y) %>% 
    nest(result = x) %>% 
    mutate(result = map_chr(result, ~paste(unlist(.x), collapse = ",")))

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