[英]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.我想使用 purrr 将一个字符字段连接到一个字符串中。
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;不确定您要使用什么purrr
function; but you can do the following in dplyr
但您可以在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)或使用nest
(回应您的评论)
d %>% group_by(y) %>%
nest(result = x) %>%
mutate(result = map_chr(result, ~paste(unlist(.x), collapse = ",")))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.