检测字符向量中的字母顺序

时间:2016-11-10 09:05:55

标签: r sorting

我有几个像这样的字符向量:

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

lastname的最后4个元素按字母顺序排列。 我想分割按字母顺序开始的向量。 因此,结果如下:

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

按字母顺序排列的部分始终位于末尾,但长度可能不同。

任何帮助都非常感谢!

2 个答案:

答案 0 :(得分:2)

我们可以创建一个逻辑索引,然后通过索引split创建一个list vector个。{/ p>

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"

答案 1 :(得分: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"