Reputation: 335
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!
Upvotes: 2
Views: 199
Reputation: 23101
This will also work:
pos <- tail(which(sapply(1:(length(lastname)-1), function(i) lastname[i] < lastname[i+1])==FALSE),1)
lastname[1:pos]
# [1] "Smith" "Johnson" "Williams" "Moore" "Taylor" "Jones"
lastname[(pos+1):length(lastname)]
# [1] "Brown" "Davis" "Miller" "Wilson"
Upvotes: 0
Reputation: 887118
We can create a logical index and then split
the vector by the index to create a list
of vector
s.
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"
Upvotes: 2