gpt4 book ai didi

r - 按升序列出文件

转载 作者:行者123 更新时间:2023-12-04 09:34:25 25 4
gpt4 key购买 nike

我有一个关于 list.files() 的简单问题功能。我有一个文件夹,其中包含以这种方式命名的文件列表:

DF2.txt
DF3.txt
DF4.txt
DF5.txt
.......
.......



当我粘贴以下字符串时,
files <- list.files(pattern = ".txt")

该向量按以下顺序返回值:

"DF10.txt"
"DF11.txt"
"DF12.txt"
........
........
"DF2.txt"
"DF20.txt"
"DF21.txt"
.........
.........
"DF3.txt"
"DF30.txt"
"DF31.txt"
..........
..........



等等。我想以数字递增的顺序列出文件,因为它们出现在文件夹中。为什么R在 list.files()之后改变文件夹中文件的顺序以及如何重新排列这些以匹配原始顺序?

最佳答案

就计算机而言,它正在正确排序。但是,您可以使用 mixedsort从“gtools”包中获取所需的排序类型:

> myFiles <- paste("file", 1:20, ".txt", sep = "")
> sort(myFiles)
[1] "file10.txt" "file11.txt" "file12.txt" "file13.txt" "file14.txt" "file15.txt"
[7] "file16.txt" "file17.txt" "file18.txt" "file19.txt" "file1.txt" "file20.txt"
[13] "file2.txt" "file3.txt" "file4.txt" "file5.txt" "file6.txt" "file7.txt"
[19] "file8.txt" "file9.txt"
> library(gtools)
> mixedsort(sort(myFiles))
[1] "file1.txt" "file2.txt" "file3.txt" "file4.txt" "file5.txt" "file6.txt"
[7] "file7.txt" "file8.txt" "file9.txt" "file10.txt" "file11.txt" "file12.txt"
[13] "file13.txt" "file14.txt" "file15.txt" "file16.txt" "file17.txt" "file18.txt"
[19] "file19.txt" "file20.txt"

以您的示例,这意味着您可以执行以下操作:
files <- list.files(pattern = ".txt")
library(gtools)
files <- mixedsort(files)

用户功能很有趣

由于编写小实用函数很容易,因此您也可以编写这样的小函数:
ListFiles <- function(pattern = ".txt") {
require(gtools)
myFiles <- list.files(pattern = pattern, )
mixedsort(myFiles)
}

然后比较:
list.files(pattern = ".txt")
ListFiles(pattern = ".txt")

关于r - 按升序列出文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15944844/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com