R:在R中重新排序多个文件路径

发布于 2025-01-28 07:38:34 字数 591 浏览 2 评论 0原文

我有100个文件,每个文件命名为“ ABC -Day -1(至100).csv”。

当我将它们读成R时,它是这样的:Day1,Day10,Day100等(请参见图1)。我知道R是这样做的,因为它是按字符对其进行排序,而不是按数字对其进行排序。有没有办法可以在数值正确的顺序(Day1,Day2,Day3,...)中重新排序路径,而无需我实际上必须手动更改我的原始文件名?

这是我到目前为止所拥有的:

filenames <- list.files(path="../STEP_ONE/Test_raw",
                    pattern="ADD_Day+.*sav",
                    full.names = TRUE)  # Reads in path of the 100 files

”图1“

I have 100 files, each named "ABC - Day - 1(to 100).csv".

When I read them into R, it is ordered like this: Day1, Day10, Day100, etc. (see figure 1). I know R does this because it is sorting it by character, not by number. Is there a way that I could reorder the path in numerically correct order (Day1, Day2, Day3, ...) without me actually having to manually change my raw file names?

Here is what I have so far:

filenames <- list.files(path="../STEP_ONE/Test_raw",
                    pattern="ADD_Day+.*sav",
                    full.names = TRUE)  # Reads in path of the 100 files

Figure 1

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

流年已逝 2025-02-04 07:38:34

让我们假设您有一个带有文件名的向量v(根据您所说的___ day __. sav)。您可以减去一天的数量,并使用以下代码重新排序名称:

# Load library
  library(stringr)
# Matrix with your files' names and the day
  tab <- as.data.frame(str_match(v, "Day\\s*(.*?)\\s*.sav"))
  # Column names
    colnames(tab) <- c("file.name", "day")
  # Day as numeric
    tab$day <- as.numeric(tab$day)
# Reorder `tab` according to $day
  tab <- tab[order(tab$day),]

Let’s suppose you have a vector v with the names of your file (according to what you said, ___Day__.sav). You can subtract the number of the day and reorder the names with the following code:

# Load library
  library(stringr)
# Matrix with your files' names and the day
  tab <- as.data.frame(str_match(v, "Day\\s*(.*?)\\s*.sav"))
  # Column names
    colnames(tab) <- c("file.name", "day")
  # Day as numeric
    tab$day <- as.numeric(tab$day)
# Reorder `tab` according to $day
  tab <- tab[order(tab$day),]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文