Convert column into a sequence

Viewed 191

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 :)

3 Answers

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))

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))

data.table

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

   name sex
1:   ab fmf
2:   bc ffm
Related