Reputation: 2533
My question is similar to this question:How to change the order of display of list.files(): for example based on part of the whole name of files
but my case is differnt. I used the solution provided:
a=a[order(gsub('.*_(\\d{8})[.].*','\\1',a))]
but did not work for my case because the naming in my case is different from that provided in that question.
I have several files in a directory. The naming of the files is complex,for instance :
file.img
file.img
I want to list the files so that I can work with them, it seemed that R listed them in a certain order. R ordered the files alphabetically even if the data is not ordered correctly.for example these two names of files:
How can I tell R to change the default display of list.files , and order the files based on _yearmonthday only which represents yearmonthday in all files:
to list files in R we use this :
I used:
mixsort
but did not ordered them as I want
Upvotes: 0
Views: 203
Reputation: 121588
I think you just need to change the pattern of the gsub
function. For example:
xx <- 'SM_OP_20120330T000000_20120330T235959_245_001_7_ssture.img'
gsub('.*_(\\d{8}).*','\\1',xx)
"20120330"
So , the whole solution is :
a <- list.files("D:\\semon", "*.img", full.names = TRUE)
a <- a[order(as.numeric(gsub('.*_(\\d{8}).*','\\1',a)))]
EDIT add an example:
a <- list('SM_OP_20120330T000000_20120330T235959_245_001_7_ssture.img', ##2012-mars-30
'SM_RE_20101130T000000_20110427T235959_245_001_7_ssture.img', ##2010-nov-30
'SM_RE_20100901T000000_20090127T235959_245_001_7_ssture.img', ##2010-sep-01
'SM_RE_20100904T000000_20090427T235959_245_001_7_ssture.img') ##2010-sep-04
a[order( as.numeric(gsub('.*_(\\d{8}).*','\\1',a)))]
[[1]]
[1] "SM_RE_20100901T000000_20090127T235959_245_001_7_ssture.img"
[[2]]
[1] "SM_RE_20100904T000000_20090427T235959_245_001_7_ssture.img"
[[3]]
[1] "SM_RE_20101130T000000_20110427T235959_245_001_7_ssture.img"
[[4]]
[1] "SM_OP_20120330T000000_20120330T235959_245_001_7_ssture.img"
Upvotes: 5