bill.meiner bill.meiner - 2 months ago 21
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!


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)
#[1] "Smith"    "Johnson"  "Williams" "Moore"    "Taylor"   "Jones"   

#[1] "Brown"  "Davis"  "Miller" "Wilson"