• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

在R对元素包含字母和数字的字符向量进行排序?

用户头像
it1352
帮助1

问题说明

我有一个字符数组

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.

有人可以帮我吗

正确答案

#1

试试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" 

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhecejhj
系列文章
更多 icon
同类精品
更多 icon
继续加载