I want to sort a vector of strings based on the last character in R. Lets say I have 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
[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
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
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.
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
:
lastChar <- function(str){
substr(str, nchar(str), nchar(str))
}
library(funprog)
sort_by(m, lastChar)
We can use 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"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.