2016-11-10 223 views
2

字母順序我有幾個特徵向量是這樣的:檢測的特徵向量

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

姓氏的最後4個元素是按字母順序排列。 我想分割字母順序開始的向量。 因此,其結果會是什麼樣子:

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

按字母順序排列的部分總是位於結束,但它的長度可能會有所不同。

任何幫助非常感謝!

回答

2

我們可以創建一個邏輯索引,然後split向量由索引創建listvector 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" 
0

這也將工作:

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"