在 R 中的 groupby 之后连接唯一的字符串 [英] Concatenate unique strings after groupby in R

查看:18
本文介绍了在 R 中的 groupby 之后连接唯一的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在对一个数据框进行分组并且想要连接唯一字符串.

I'm grouping a dataframe and want to concatenate unique strings.

data= data.frame(
aa=c(1,2,3,4,5,6,7,8,9,10),
bb=c('a','a','a','a','a','b','b','b','b','b'),
cc=c('hello','hello','hi','message','bye','q','w','r','r','t'))

所需的输出:

bb    cc
a     'hello hi message bye'
b     'q w r t'

目前我正在这样做(建议在这里)::>

Currently I'm doing this(suggested here):

result<- data %>% 
  group_by(bb) %>%
  mutate(body = paste0(cc, collapse = "")) %>%
  summarise(t_body = first(body)

但我得到了所有的字符串,而不是唯一的.

But I get all the strings not the unique ones.

推荐答案

cc 上使用 unique 粘贴之前,也不需要 mutate 步骤,可以直接使用summarize:

Use unique on cc before pasting it, and also no need for the mutate step, you can use summarize directly:

data %>% 
    group_by(bb) %>% 
    summarise(cc = paste(unique(cc), collapse = ' '))

# A tibble: 2 x 2
#  bb    cc                  
#  <fct> <chr>               
#1 a     hello hi message bye
#2 b     q w r t  

这篇关于在 R 中的 groupby 之后连接唯一的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆