如何在R中对元素包含字母和数字的字符向量进行排序? [英] How to sort a character vector where elements contain letters and numbers in R?

查看:42
本文介绍了如何在R中对元素包含字母和数字的字符向量进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符数组

cf <- c("V440","V457","V116","V327","V446","V108",
         "V155","V217","V120","V51","V477")

我想按降序对其进行排序,以便得到如下输出:

I would like to sort it in descending order so that I will have an output like this:

V51
V108
V116
V120
V155
V217
V327
V440
V446
V457
V477

我试过这样的sort.list()

cf[sort.list(cf)]

得到这个答案:

[1] "V108" "V116" "V120" "V155" "V217" "V327" "V440" "V446" "V457" "V477" "V51" 

并且还尝试了 order() 并得到了相同的结果.

and also tried order() and got same result.

有人可以帮我吗

推荐答案

试试gtools"包中的mixedsort:

Try mixedsort from the "gtools" package:

> # install.packages("gtools") ## Uncomment if not already installed
> library(gtools)
> mixedsort(cf)
 [1] "V51"  "V108" "V116" "V120" "V155" "V217" "V327" "V440" "V446" "V457" "V477"

<小时>

如果您不想使用 mixedsort(不知道为什么不使用),并且如果您的向量具有非常一致的模式(例如字母后跟数字),您也可以尝试这样的事情.(注意:相对未经测试.)


If you don't want to use mixedsort (not sure why one wouldn't), and if your vector has a pretty consistent pattern (eg letters followed by numbers), you can also probably try something like this. (Note: Relatively untested.)

newvec <- c("V440", "V457", "V116", "V327", "V446", "V108", "V155", 
            "V217", "V120", "V51", "V477", "B22", "A10", "Z01")

newvec[order(gsub("([A-Z]+)([0-9]+)", "\1", newvec), 
             as.numeric(gsub("([A-Z]+)([0-9]+)", "\2", newvec)))]
#  [1] "A10"  "B22"  "V51"  "V108" "V116" "V120" "V155" "V217" "V327" "V440"
# [11] "V446" "V457" "V477" "Z01" 

这篇关于如何在R中对元素包含字母和数字的字符向量进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆