'R: Reordering Multiple File Path in an object in R [duplicate]

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



Solution 1:[1]

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),]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Peter Mortensen