datadan
datadan

Reputation: 55

How can I reorder a dataframe such that the elements within each index are ordered alphanumerically?

a <- c("rey,ben","ben,rey","jodi,ben","ben,jodi","rey","bob,rey,ben","rey,bob,ben")
b <- c(1,1,2,2,3,4,4)
c <- c(13,17,13,20,21,14,17)
test1 <- data.frame(Staff=a,Value=b,Code=c)

> str(test1)
'data.frame':   5 obs. of  3 variables:
 $ Staff: Factor w/ 7 levels "ben,jodi","ben,rey",..: 5 2 3 1 4
 $ Value: num  1 1 2 2 3
 $ Code : num  13 17 13 20 21

> test1
         Staff Value Code
 1     rey,ben     1   13
 2     ben,rey     1   17
 3    jodi,ben     2   13
 4    ben,jodi     2   20
 5         rey     3   21
 6 bob,rey,ben     4   14
 7 rey,bob,ben     4   17

How can I reorder the levels within test1$Staff such that the elements within each index are ordered alphanumerically? This is a small subset, I'll have many name and length combinations 1,2,3,4 names long with over 10 names. I want to reorder so that that records that were entered as rey,ben will become ben,rey sorting ben before rey.

Desired outcome:

          Staff Value Code
 1     ben,rey     1   13
 2     ben,rey     1   17
 3    ben,jodi     2   13
 4    ben,jodi     2   20
 5         rey     3   21
 6 ben,bob,rey     4   14
 7 ben,bob,rey     4   17

Upvotes: 1

Views: 51

Answers (1)

akrun
akrun

Reputation: 887173

As @pascal mentioned, the desired output may not be correct. Assuming that we understand the question, split the 'Staff' column by the delimiter , to get a list, then we sort the elements, and paste it together.

test1$Staff <- sapply(strsplit(as.character(test1$Staff), ','), 
              function(x) toString(sort(x)))
test1
#          Staff Value Code
#1      ben, rey     1   13
#2      ben, rey     1   17
#3     ben, jodi     2   13
#4     ben, jodi     2   20
#5           rey     3   21
#6 ben, bob, rey     4   14
#7 ben, bob, rey     4   17

If we need a factor column,

test1$Staff <- factor(test1$Staff)

NOTE: The toString is a wrapper for paste(., collapse=', '). There is a space after a ,. In case, we need to make it congested without the space, we can replace the toString with paste(x, collapse=',').

Upvotes: 3

Related Questions