这个问题在这里已经有了答案:
Collapse / concatenate / aggregate a column to a single comma separated string within each group
(4 个回答)
4年前关闭。
我有一个看起来像这样的数据框
> data <- data.frame(foo=c(1, 1, 2, 3, 3, 3), bar=c('a', 'b', 'a', 'b', 'c', 'd'))
> data
foo bar
1 1 a
2 1 b
3 2 a
4 3 b
5 3 c
6 3 d
我想创建一个新列 bars_by_foo,它是 bar 的值与 foo 的连接。所以新数据应该是这样的:
foo bar bars_by_foo
1 1 a ab
2 1 b ab
3 2 a a
4 3 b bcd
5 3 c bcd
6 3 d bcd
我希望以下内容有效:
p <- function(v) {
Reduce(f=paste, x = v)
}
data %>%
group_by(foo) %>%
mutate(bars_by_foo=p(bar))
但是那个代码给了我一个错误
Error: incompatible types, expecting a character vector
.我究竟做错了什么?
最佳答案
你可以简单地做
data %>%
group_by(foo) %>%
mutate(bars_by_foo = paste0(bar, collapse = ""))
没有任何辅助功能
关于r - 使用 dplyr 按组连接字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38514988/