简体   繁体   English

如何根据 R 中的最后一个字符对字符串向量进行排序

[英]How to sort a vector of strings based on the last Character in R

I want to sort a vector of strings based on the last character in R.我想根据 R 中的最后一个字符对字符串向量进行排序。 Lets say I have m可以说我有 m

m <- names(df)
m
[1] "test_1_p" "test_2_n" "test_3_p" "test_4_p" "test_5_n"

For reproduciblity:为了重现性:

m <- c("test_1_p","test_2_n","test_3_p","test_4_p","test_5_n")

Now my Desired output would be现在我想要的 output 将是

[1] "test_2_n" "test_5_n" "test_1_p" "test_3_p" "test_4_p" 

I tried to work with strsplit , but couldn't get it to work我尝试使用strsplit ,但无法正常工作

r = strsplit(m,"_")
sorting_df = data.frame(r)
sort(sorting_df[3,])

I belief there has to be a fairly simple solution to that comparable to python where one could easily do it like this我相信必须有一个相当简单的解决方案来与 python 相媲美,人们可以像这样轻松地做到这一点

lst = ["test_1_p","test_2_n","test_3_p","test_4_p","test_5_n"]
sorted(lst, key=lambda x: x[-1])

Edit All provided Solutions work thank you very much.编辑所有提供的解决方案非常感谢您。 Just accepted the first one.只接受了第一个。

You can get the last part from the string and use it's order to subset the string.您可以从字符串中获取最后一部分并使用它的order对字符串进行子集化。

m[order(sub('.*_', '', m))]
#[1] "test_2_n" "test_5_n" "test_1_p" "test_3_p" "test_4_p"

Does this work:这是否有效:

m[order(substr(m,nchar(m),nchar(m)))]
[1] "test_2_n" "test_5_n" "test_1_p" "test_3_p" "test_4_p"

Here is a solution with funprog::sort_by :这是funprog::sort_by的解决方案:

lastChar <- function(str){
  substr(str, nchar(str), nchar(str))
}
library(funprog)
sort_by(m, lastChar)

We can use stri_extract_last我们可以使用stri_extract_last

library(stringi)
m[order(stri_extract_last(m, regex = "\\w"))]
#[1] "test_2_n" "test_5_n" "test_1_p" "test_3_p" "test_4_p"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM