DeJay DeJay - 1 year ago 68
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...

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

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

Answer Source

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",

You could do a transformation like

dd$V2<-sapply(lapply(strsplit(dd$V1,", "), sort), paste, collapse=", ")
#                      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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download