DeJay DeJay - 4 months ago 7
R Question

How to sort a string of names alphabetically in R?

Say I have a df column that contains a random list of names in each row...

df$Column
Row 1 Sam, Brad, Tom
Row 2 James, Alex, Sarah
Row 3 Bianca, Jesse, Tim
... ...
Row n Xavier, Trevor, Claire


How would I sort each list of names alphabetically so that I end up with the following result...

df$Column
Row 1 Brad, Sam, Tom
Row 2 Alex, James, Sarah
Row 3 Bianca, Jesse, Tim
... ...
Row n Claire, Trevor, Xavier

Answer

If you really have a single column with a string that has commas like this

dd<-read.table(text="Sam, Brad, Tom
James, Alex, Sarah
Bianca, Jesse, Tim
Xavier, Trevor, Claire", sep="\t", as.is=T)

You could do a transformation like

dd$V2<-sapply(lapply(strsplit(dd$V1,", "), sort), paste, collapse=", ")
dd
#                      V1                     V2
#1         Sam, Brad, Tom         Brad, Sam, Tom
#2     James, Alex, Sarah     Alex, James, Sarah
#3     Bianca, Jesse, Tim     Bianca, Jesse, Tim
#4 Xavier, Trevor, Claire Claire, Trevor, Xavier