bill.meiner bill.meiner - 1 year ago 85
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 Source

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"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download