我有一个字符数组
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()
并获得了相同的结果。
有人可以帮助我吗
答案 0 :(得分:40)
从“gtools”包中试用mixedsort
:
> # 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
(不确定为什么不会),如果您的矢量具有相当一致的模式(例如字母后跟数字),您也可以尝试类似这个。 (注意:相对未经测试。)
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"
答案 1 :(得分:36)
这里有很多正确的答案,这是另一种方式,只是为了好玩。
cf[order(nchar(cf), cf)]
# [1] "V51" "V108" "V116" "V120" "V155" "V217" "V327" "V440" "V446" "V457" "V477"
答案 2 :(得分:10)
使用exports.addMessage = functions.https.onCall((data, context) => {
// ...
const text = data.text;
const push = data.push;
// ...
});
函数(来自str_sort
包装)的代码行中的另一个解决方案
stringr
# install.packages("stringr") ## Uncomment if not already installed
library(stringr)
str_sort(cf, numeric = TRUE)
答案 3 :(得分:5)
只需刮掉前面的“V”字符即可构建排序向量。不需要额外的花哨工具。
vals <- as.numeric(gsub("V","", cf))
cf[order(vals)]
[1] "V51" "V108" "V116" "V120" "V155" "V217" "V327" "V440" "V446"
[10] "V457" "V477"
答案 4 :(得分:3)
R按字母顺序正确排序字符串,这就是你得到结果的原因。
除了@Ananda非常好的答案,如果你想使用基数R,你可以使用strsplit
从每个字符串中删除“V”,然后使用as.numeric
将字符串转换为整数:
vals <- as.numeric(sapply(cf, FUN=function(x){strsplit(x, "V")[[1]][2]}))
现在,您可以使用vals
cf[order(vals)]
答案 5 :(得分:1)
这是一个利用names
和sort
的基本方法(Ananda很漂亮):
cf <- c("V440","V457","V116","V327","V446","V108",
"V155","V217","V120","V51","V477")
cf2 <- as.numeric(gsub("[^[:digit:]]", "", cf))
names(cf2) <- seq_along(cf2)
cf[as.numeric(names(sort(cf2)))]
## > cf[as.numeric(names(sort(cf2)))]
## [1] "V51" "V108" "V116" "V120" "V155" "V217" "V327"
## [8] "V440" "V446" "V457" "V477"