I agree with dupe flag, but I had already submitted my answer; btw, the first expected output table is a dupe of Collapse / concatenate / aggregate a column to a single comma separated string within each group
. Happy to delete if advised in a comment.
To reproduce your first output
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
To reproduce your second output
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
Sample data
df <- read.table(text =
"surname name
a b
a a
a c
b a
b b
b c", header = T)