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

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

我有一个字符数组

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

我想按降序排序,以便我有这样的输出:

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()了同样的结果。

有谁可以帮助我吗


慕田峪4524236
浏览 4739回答 3
3回答

慕沐林林

试试mixedsort“gtools”套餐:> # install.packages("gtools") ## Uncomment if not already installed> library(gtools)> mixedsort(cf)&nbsp;[1] "V51"&nbsp; "V108" "V116" "V120" "V155" "V217" "V327" "V440" "V446" "V457" "V477"如果你不想使用mixedsort(不确定为什么不会),如果你的矢量有一个相当一致的模式(例如字母跟数字),你也可以尝试这样的事情。(注意:相对未经测试。)newvec <- c("V440", "V457", "V116", "V327", "V446", "V108", "V155",&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "V217", "V120", "V51", "V477", "B22", "A10", "Z01")newvec[order(gsub("([A-Z]+)([0-9]+)", "\\1", newvec),&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;as.numeric(gsub("([A-Z]+)([0-9]+)", "\\2", newvec)))]#&nbsp; [1] "A10"&nbsp; "B22"&nbsp; "V51"&nbsp; "V108" "V116" "V120" "V155" "V217" "V327" "V440"# [11] "V446" "V457" "V477" "Z01"&nbsp;

潇潇雨雨

这里有很多正确的答案,这是另一种方式,只是为了好玩。cf[order(nchar(cf),&nbsp;cf)]#&nbsp;[1]&nbsp;"V51"&nbsp;&nbsp;"V108"&nbsp;"V116"&nbsp;"V120"&nbsp;"V155"&nbsp;"V217"&nbsp;"V327"&nbsp;"V440"&nbsp;"V446"&nbsp;"V457"&nbsp;"V477"

慕的地10843

使用str_sort函数的一行代码中的另一个解决方案(来自&nbsp;stringrpackg)#&nbsp;install.packages("stringr")&nbsp;##&nbsp;Uncomment&nbsp;if&nbsp;not&nbsp;already&nbsp;installedlibrary(stringr)str_sort(cf, numeric = TRUE)[1]&nbsp;"V51"&nbsp;&nbsp;"V108"&nbsp;"V116"&nbsp;"V120"&nbsp;"V155"&nbsp;"V217"&nbsp;"V327"&nbsp;"V440"&nbsp;"V446"&nbsp;"V457"&nbsp;"V477"
打开App,查看更多内容
随时随地看视频慕课网APP