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

如何将list.files()获取的文件列表按正确日期顺序排序?

问题描述

使用list.files()读取NC文件时,文件名按字符串排序导致月份顺序混乱:

f <- list.files(pattern="*.nc")
f
# [1] "te1971-1.nc"  "te1971-10.nc" "te1971-11.nc" "te1971-12.nc"
# [5] "te1971-2.nc"  "te1971-3.nc"  "te1971-4.nc"  "te1971-5.nc" 
# [9] "te1971-6.nc"  "te1971-7.nc"  "te1971-8.nc"  "te1971-9.nc"

尝试用mixedsort()排序却得到倒序结果:

myFiles <- paste("te", i, "-", c(1:12), ".nc", sep = "")
mixedsort(myFiles)
# [1] "te1971-12.nc" "te1971-11.nc" "te1971-10.nc" "te1971-9.nc" 
# [5] "te1971-8.nc"  "te1971-7.nc"  "te1971-6.nc"  "te1971-5.nc" 
# [9] "te1971-4.nc"  "te1971-3.nc"  "te1971-2.nc"  "te1971-1.nc" 

需要修正排序结果,得到按月份1-12正序排列的文件列表。

解决方案

方法1:调整mixedsort的排序方向

mixedsort()默认升序,若结果为倒序,直接指定decreasing=FALSE即可:

library(gtools)
myFiles <- paste("te", 1971, "-", 1:12, ".nc", sep = "")
mixedsort(myFiles, decreasing = FALSE)

输出正序列表:

# [1] "te1971-1.nc"  "te1971-2.nc"  "te1971-3.nc"  "te1971-4.nc" 
# [5] "te1971-5.nc"  "te1971-6.nc"  "te1971-7.nc"  "te1971-8.nc" 
# [9] "te1971-9.nc"  "te1971-10.nc" "te1971-11.nc" "te1971-12.nc"

方法2:提取月份数值排序(基础R实现)

从已读取的文件名中提取-后的月份数字,以此为依据排序:

# 提取月份数字
months <- as.integer(sub("te\\d+-([0-9]+)\\.nc", "\\1", f))
# 按月份正序排列文件列表
f_sorted <- f[order(months)]
f_sorted

方法3:直接生成正序文件名

已知文件名规则(固定年份+1-12月),可直接生成正序列表,无需额外排序:

year <- 1971
myFiles_sorted <- paste0("te", year, "-", 1:12, ".nc")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 16:20:38