在R中的groupby之后连接唯一字符串 [英] Concatenate unique strings after groupby in R
本文介绍了在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)
但是我得到的所有字符串不是 unique 。
But I get all the strings not the unique ones.
推荐答案
在<$ c $上使用独特
c> cc 粘贴之前,也不需要变异
步骤,您可以直接使用总结
:
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屋!
查看全文