How can I read the files in a directory in sorted order using R?
Why not retrieve all files (with a particular pattern) with list.files() and then sort that. Then you retrieve the files from the sorted vector, which gives them to you in correctly sorted order. This has the advantage that it also works when numbers are missing from the 1:365 sequence
Something like:
myFiles <- list.files(pattern = "^Climate_Rad_") #all files starting with Climate_
myFiles <- sort(myFiles)
# then read them in, for instance through
for (fileNames in myFiles) {READ.IN.AND.DO.YOUR.MAGIC.ON.THEM}
sorting files and read according to basename in R
Just use order
to get an ordered vector of indices to rearrange the original vector of files:
files <- c("path/b01.csv","path/a01.csv", "path/a02.csv")
files[order(basename(files))]
[1] "path/a01.csv" "path/a02.csv" "path/b01.csv"
list files in ascending order
As far as computers are concerned, it is sorting correctly. However, you can used mixedsort
from the "gtools" package to get the type of sorting you want:
> 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"
With your example, that means you can do:
files <- list.files(pattern = ".txt")
library(gtools)
files <- mixedsort(files)
User functions are fun
Since it's easy to write little utility functions, you can also write a little function like this:
ListFiles <- function(pattern = ".txt") {
require(gtools)
myFiles <- list.files(pattern = pattern, )
mixedsort(myFiles)
}
Then, compare:
list.files(pattern = ".txt")
ListFiles(pattern = ".txt")
Reading and listing objects in the order they appear in the source file in R
There's no way to get the order of variable definition after sourcing the file without explicitly recording the order in the file itself. One way to do this would be to put the variables in a list
.
How to sort files list by date?
You can use the file.info
function to obtain details on your files. Once you have those details, you can sort the files accordingly. For example,
details = file.info(list.files(pattern="*.csv"))
gives a data frame containing, inter alia, modification and creation times. You can sort that data frame however you want. Here I sort according to modification time, mtime
:
details = details[with(details, order(as.POSIXct(mtime))), ]
files = rownames(details)
Reading files in directory in sorted order Python
Try sorting the files list using sorted
.
Ex:
root_dir = r'C:\Users\ab\pythonfiles\Compressed_images'
for root, dirs, files in os.walk(root_dir):
for file in sorted(files, key=lambda x: int(x.split(".")[0])):
print('For file: \n', file)
Sorting files in the directory including case sensitivity in C
#include <stdio.h>
#include <dirent.h>
#include <string.h>
int main(void)
{
char array[50][30]={};
int i=0, j=0, k=0;
DIR *d;
struct dirent *dir;
d = opendir(".");
printf("d: %d \n",d);
if (d)
{
while ((dir = readdir(d)) != NULL)
{
strcpy(array[i], dir->d_name);
i++;
}
for (k = 0; k <= i; k++) /* Sorting files alphabetically */
for (j = k + 1; j <= i; j++)
{
if (strcasecmp(array[k], array[j]) > 0)
{
strcpy(tmp, array[k]);
strcpy(array[k], array[j]);
strcpy(array[j], tmp);
}
}
closedir(d);
}
for (int a = 0 ; a < i ; a++)
{
printf("%s \n",array[a]);
}
return 0;
}
Related Topics
Numbered Code Chunks in Rmarkdown
How to Show a Loading Screen When the Output Is Being Calculated in a Background Process
Calculating Prediction Accuracy of a Tree Using Rpart's Predict Method
R: Clustering Results Are Different Everytime I Run
Creating Igraph with Isolated Nodes
Data.Table Join and J-Expression Unexpected Behavior
Unzip Password Protected Zip Files in R
Differencebetween Scale Transformation and Coordinate System Transformation
"Error: Continuous Value Supplied to Discrete Scale" in Default Data Set Example Mtcars and Ggplot2
Ggplot2: How to Reduce Space Between Narrow Width Bars, After Coord_Flip, and Panel Border
Independently Move 2 Legends Ggplot2 on a Map
Pass String as Name of Attached Data Column Name
Ubuntu 16.04 R Installation: Configure: Gdal-Config Not Found or Not Executable
Apply a Function to All Variables Starting with Specific Pattern in R
Outputing N Tables in Shiny, Where N Depends on the Data