[R] Reorder file names read by list.files function

Jeff Newmiller jdnewm|| @end|ng |rom dcn@d@v|@@c@@u@
Tue Oct 9 17:29:56 CEST 2018


Instead of changing the order in which you read the files, perhaps your analysis will work if you sort the data after you read it in. This may require that you add the month names as a column in the data frames, or you may already have dates in the data that you could sort by.

One idea:

fnames <- paste0( month.name, ".PDF" )
resultdf <- do.call( rbind, lapply(fnames, function(fn) { read.csv( file.path( "datadir", fn ), as.is=TRUE ) } )

but that only works if there are exactly 12 files. If there could be fewer, perhaps:

fnames <- list.files( "datadir" )
sfnames <- fnames[ match( sub("\\.PDF", "", fnames ), month.name ) ]


On October 9, 2018 6:44:21 AM PDT, Ek Esawi <esawiek using gmail.com> wrote:
>Hi All--
>
>I used base R list.file function to read files from a directory. The
>file names are months (April, August, etc). That's the system reads
>them in alphabetical order., but i want to reordered them in calendar
>order (January, February, ...December).. I thought i might be able to
>do it via RegEx or possibly gtools package, I am wondering if there is
>an easier way.
>
>Thanks--EK
>
>Example
>path = "C:/Users/name/Downloads/MyFiles"
>file.names <- dir(path, pattern =".PDF")
>
>Example output
>Output:
>"February.PDF"  "January.PDF" "March.PDF"
>Desired output
>"January.PDF"  "February.PDF" "March.PDF"
>
>______________________________________________
>R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
>https://stat.ethz.ch/mailman/listinfo/r-help
>PLEASE do read the posting guide
>http://www.R-project.org/posting-guide.html
>and provide commented, minimal, self-contained, reproducible code.

-- 
Sent from my phone. Please excuse my brevity.




More information about the R-help mailing list