[英]Use purrr to collapse a vector of characters into a string of character
我想使用 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 = ",")))
不確定您要使用什么purrr
function; 但您可以在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
或使用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.