2

I have a dataframe which looks like this:

name sex
ab f
ab m
ab f
bc f
bc f
bc m

I want to convert the observations of the column 'sex' as string. The outcome should look like:

name seq
ab fmf
bc ffm

Any help is highly appreciated! Thanks in advance :)

Peter
  • 11,500
  • 5
  • 21
  • 31
Roy
  • 21
  • 2
  • Related: [Collapse / concatenate / aggregate a column to a single comma separated string within each group](https://stackoverflow.com/questions/15933958/collapse-concatenate-aggregate-a-column-to-a-single-comma-separated-string-w) – markus Apr 20 '21 at 08:44

3 Answers3

3

This might work for you:


library(tidyverse)

df %>%
  group_by(name) %>%
  summarise(sex = paste(sex, collapse = "")) %>%
  ungroup()

# A tibble: 2 x 2
  name  sex  
  <chr> <chr>
1 ab    fmf  
2 bc    ffm 

Data

df <- structure(list(name = c("ab", "ab", "ab", "bc", "bc", "bc"), 
               sex = c("f", "m", "f", "f", "f", "m")), class = "data.frame", row.names = c(NA, -6L))
DJV
  • 4,743
  • 3
  • 19
  • 34
KERO
  • 705
  • 6
  • 15
2

You can try aggregate

> aggregate(sex ~ ., df, paste0, collapse = "")
  name sex
1   ab fmf
2   bc ffm

Data

> dput(df)
structure(list(name = c("ab", "ab", "ab", "bc", "bc", "bc"), 
    sex = c("f", "m", "f", "f", "f", "m")), class = "data.frame", row.names = c(NA,
-6L))
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
2

data.table

setDT(df)[, list(sex = paste0(sex, collapse = "")), by = name]

   name sex
1:   ab fmf
2:   bc ffm
Yuriy Saraykin
  • 8,390
  • 1
  • 7
  • 14