How to force R to read in numerical order?
I have several files in one folder and I want to rename them,I noticed that R reads in alphbatical order, so I used the command mixedsort and it worked but when I checked the results I found that the files were read in a different order not numerically. The name of the first file is Daily_NPP1.bin up to Daily_NPP365.bin
a<- list.files("C:\\New folder (6)", "*.bin", full.names = TRUE) k<- mixedsort(a)#### load package feild b <- sprintf("C:carbonflux\\Daily_Rh%d.bin", seq(k)) file.rename(a, b)
How do I force R to read in numerical order?
If renaming is all you want to do you could just do the following, regardless of sorting.
b <- sub("^.*?([0-9]+)\\.bin$", "C:\\\\carbonflux\\\\Daily_Rh\\1.bin", a) file.rename(a, b)
The first argument to sub extracts the numbers at the end of the file names, and the second pastes it into the new file name template (at the position of \\1). All the \\\\ are needed to escape the backslashes properly.
Here is a way to order the vector without renaming the files:
# Replication of data: a <- sort(paste0("Daily_NPP",1:365,".bin")) # Extract numbers and order: a <- a[order(as.numeric(gsub("[^0-9]","",a)))]