bill.meiner bill.meiner - 22 days ago 15
R Question

Detect alphabetical order in character vector

I have several character vectors like this:

lastname <- c("Smith" ,"Johnson" , "Williams" , "Moore" , "Taylor", "Jones"
, "Brown" , "Davis" , "Miller" , "Wilson" )


lastname's last 4 elements are in alphabetical order.
I want to split the vector where the alphabetical order starts.
Thus, the result would look like:

lastname1 <- c("Smith" ,"Johnson" , "Williams" , "Moore" , "Taylor", "Jones")
lastname2 <- c("Brown" , "Davis" , "Miller" , "Wilson" )


The part in alphabetical order is always located at the end but it's length may differ.

Any help greatly appreciated!

Answer

We can create a logical index and then split the vector by the index to create a list of vectors.

i1 <- rev(cumsum(c(TRUE, diff(rank(rev(lastname))) >0))==1)
split(lastname, i1)
#$`FALSE`
#[1] "Smith"    "Johnson"  "Williams" "Moore"    "Taylor"   "Jones"   

#$`TRUE`
#[1] "Brown"  "Davis"  "Miller" "Wilson"
Comments