Home > Software engineering >  How to separate a list of names into columns alphabetically?
How to separate a list of names into columns alphabetically?

Time:04-09

I have a list of names, and I would like to write code that splits it into alphabetical columns. For example, the list I have here,

>NameSet2
 1 Andrikima   
 2 Anucader    
 3 Chlyger     
 4 Clunature   
 5 Dathroe     
 6 Dayne Knight
 7 Discroder   
 8 Djinny      
 9 Doomshire   
10 Doomspire   
... with 73 more rows

...would turn into something like

A        B        C         D
Anucader,         Chlyger,  Dathroe
                  Clunature, Dayne Knight

and so forth.

CodePudding user response:

one approach:

library(dplyr)
library(tidyr)

data.frame(name = c('Bob', 'Alice', 'Billy')) %>%
    arrange(name) %>%
    mutate(first_letter = substr(name, 1, 1)) %>%
    group_by(first_letter) %>%
    summarise(name = paste(name, collapse = ', ')) %>%
    pivot_wider(names_from = first_letter,
                values_from = name)

CodePudding user response:

If you want a list with individual values, I'd go with @akrun's suggestion (it's what split is intended to do). If you want the named vector with comma separated string you can extend the answer with:

split(NameSet2, substr(NameSet2, 1, 1)) |>
  purrr::map_chr(~paste(.x, collapse = ", "))
  •  Tags:  
  • r
  • Related