我的data_frame如下(姓-名对是唯一的)
surname name
a b
a a
a c
b a
b b
b c
我想合并数据并进行类似的转换
surname name
a b,a,c
b a,b,c
或者那样(如果更简单的话)
surname name_1 name_2 name_3
a b a c
b a b c
我该怎么做?
答案 0 :(得分:0)
我同意dupe flag,但是我已经提交了答案;顺便说一句,第一个预期输出表是Collapse / concatenate / aggregate a column to a single comma separated string within each group 的重复。如果有建议,很高兴删除它。
要重现您的第一个输出
library(tidyverse)
df %>%
group_by(surname) %>%
summarise(name = toString(name))
## A tibble: 2 x 2
# surname name
# <fct> <chr>
#1 a b, a, c
#2 b a, b, c
再现第二个输出
df %>%
group_by(surname) %>%
mutate(n = paste0("name_", 1:n())) %>%
spread(n, name)
## A tibble: 2 x 4
## Groups: surname [2]
# surname name_1 name_2 name_3
# <fct> <fct> <fct> <fct>
#1 a b a c
#2 b a b c
df <- read.table(text =
"surname name
a b
a a
a c
b a
b b
b c", header = T)