You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言如何按年份优先、学期次之的规则对目录文件列表排序

实现方法

你当前使用的默认排序、自然排序逻辑都是从左到右逐位匹配字符串,因此会优先将Archivo_1开头的所有文件排在最前,再排列Archivo_2开头的文件,不符合你「先按年份排序、同年份按S前的数字排序」的需求,可通过显式提取排序字段实现目标结果:

方法1:基础R实现(无需安装第三方包)

# 构造初始文件名向量
myFiles <- paste0("Archivo_", c(1:2),"S",rep(c(2010:2015), each=2), ".txt")

# 提取两个排序维度:S后的年份、S前的数字
file_year <- as.integer(sub(".*S(\\d{4})\\.txt", "\\1", myFiles))
file_num <- as.integer(sub("Archivo_(\\d+)S.*", "\\1", myFiles))

# 按年份升序、数字升序排列
sorted_files <- myFiles[order(file_year, file_num)]

方法2:搭配stringr包实现(代码更简洁)

library(stringr)
sorted_files <- myFiles[order(
  str_extract(myFiles, "\\d{4}"), 
  str_extract(myFiles, "(?<=_)\\d+(?=S)")
)]

运行上述代码后输出的sorted_files即可得到你期望的排序结果:

print(sorted_files)
#  [1] "Archivo_1S2010.txt" "Archivo_2S2010.txt" "Archivo_1S2011.txt"
#  [4] "Archivo_2S2011.txt" "Archivo_1S2012.txt" "Archivo_2S2012.txt"
#  [7] "Archivo_1S2013.txt" "Archivo_2S2013.txt" "Archivo_1S2014.txt"
# [10] "Archivo_2S2014.txt" "Archivo_1S2015.txt" "Archivo_2S2015.txt"

内容的提问来源于stack exchange,提问作者Rodrigo Badilla

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 09:54:04