[R] about reading files in order

Henrik Bengtsson henrik.bengtsson at gmail.com
Thu Jun 29 21:47:45 CEST 2017


You can use:

> files <- list.files(path = "folder01")
> files <- gtools::mixedsort(files)

to order the files in a "human-friendly" order rather than
lexicographic order (which sort() provides).

FYI 1; it's preferred to use file.path("folder01", list[i]) rather
than paste('folder01',lists[i],sep='/').

FYI 2; if you use list.files(path = "folder01", full.names = TRUE),
you get the full paths rather name just the file names, i.e. you don't
have to use file.path().

/Henrik

On Thu, Jun 29, 2017 at 12:04 PM, lily li <chocold12 at gmail.com> wrote:
> Hi R users,
> I have a question about opening the txt files and putting them into a
> matrix. The txt files are in the folder01, while they have the name
> file.1.txt, file.2.txt, file.3.txt, etc. There are about 200 such text
> files. Each txt file contains one value inside. When I tried to use the
> code below, I found that the txt files are not in order, from 1, 2, 3, to
> 200. Rather, they are in the order 1, 10, 100, 101, etc. How to change it
> so that they are in order? Thanks for your help.
>
> temp <- list.files('folder01',pattern="*.txt"
> name.list <-lapply(paste('folder01',temp,sep='/'),read.table,head=F)
> library(data.table)
> files.matrix <-rbindlist(name.list)
>
> Also, when use the code below, how to complete it so that the values of the
> files are stored in a matrix?
> lists = list.files('folder01')
> for (i in 1:length(lists)){
>   file <- read.table(paste('folder01',lists[i],sep='/'),head=F)
>   print(file)
> }
>
>         [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at 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.



More information about the R-help mailing list