-1

I've got data_frame as below (surname-name pairs are unique)

surname name
a       b
a       a
a       c
b       a
b       b
b       c

I want to consolidate data and transform for something like that

surname name
a       b,a,c
b       a,b,c

or that (if it would be simpler)

surname name_1 name_2 name_3
a       b      a      c
b       a      b      c

How can I do this?

anba
  • 543
  • 1
  • 4
  • 7

1 Answers1

0

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)
Maurits Evers
  • 49,617
  • 4
  • 47
  • 68