使用group_by连接字符串并在r中进行汇总 [英] Concatenating strings using group_by and summarise in r
问题描述
我正在尝试根据分组将一列字符串连接在一起.我使用的代码看起来与其他人使用的代码完全相同(例如使用dplyr连接一列),但是它不起作用,我也不知道为什么.
I am trying to concatenate a column of strings together based on a grouping. I'm using code that seems identical to me to what others have used (e.g. use dplyr to concatenate a column) but it isn't working, and I can't figure out why.
a = tibble(
x = c(1,2,1,2),
z = c('1','2','3','4')
)
a %>% group_by(x) %>% summarise(val=paste(z, collapse=" "))
赠予:
val
1 1 2 3 4
就好像只有一组.但是,当我执行其他功能时,分组工作正常:
It acts as if there was only one group. Yet when I do a different function, the grouping works properly:
a %>% group_by(x) %>% tally()
# A tibble: 2 × 2
x n
<dbl> <int>
1 1 2
2 2 2
知道可能是什么问题吗?
Any idea what the issue might be?
推荐答案
可能还加载了 plyr
程序包,并从 dplyr中屏蔽了
,因为它们都具有相同的函数名称.一种选择是使用 summarise
函数 ::
从 dplyr
包
It could be that plyr
package was also loaded and masked the summarise
function from dplyr
as both of them have the same function name. One option is to use ::
to specify the function from the dplyr
package
a %>%
group_by(x) %>%
dplyr::summarise(val=paste(z, collapse=" "))
# A tibble: 2 x 2
# x val
# <dbl> <chr>
#1 1 1 3
#2 2 2 4
这篇关于使用group_by连接字符串并在r中进行汇总的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!