3 回答
TA贡献2016条经验 获得超9个赞
试试mixedsort“gtools”套餐:
> # 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"
TA贡献1833条经验 获得超4个赞
这里有很多正确的答案,这是另一种方式,只是为了好玩。
cf[order(nchar(cf), cf)]# [1] "V51" "V108" "V116" "V120" "V155" "V217" "V327" "V440" "V446" "V457" "V477"
TA贡献1785条经验 获得超8个赞
使用str_sort
函数的一行代码中的另一个解决方案(来自 stringr
packg)
# install.packages("stringr") ## Uncomment if not already installedlibrary(stringr)
str_sort(cf, numeric = TRUE)
[1] "V51" "V108" "V116" "V120" "V155" "V217" "V327" "V440" "V446" "V457" "V477"
- 3 回答
- 0 关注
- 4911 浏览
添加回答
举报