Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
223 views
in Technique[技术] by (71.8m points)

r - How to change the order of display of list.files(): for example based on part of the whole name of files

I have several nc files in a directory. The naming of the files is complex,for instance :

 LPRM-AMSR_E_L3_D_SOILM3_V002-20120601T214436Z_20100801.nc

I want to list the files so that I can work with them,it seemed that R listed them ina certain order.

How can I tell R change the default display of list.files , and order them the files based on _yearmonthday only which represents yearmonthday in all files

LPRM-AMSR_E_L3_D_SOILM3_V002-20120601T214436Z _20100801

to list files in R I use this :

a<-list.files("D:\semon", "*.nc", full.names = TRUE)

I get this :

[1] "D:\LPRM-AMSR_E_L3_D_SOILM3_V002-20120603T170757Z_20110916.nc"
[2] "D:\/LPRM-AMSR_E_L3_D_SOILM3_V002-20120603T194524Z_20110917.nc"
[3] "D:\/LPRM-AMSR_E_L3_D_SOILM3_V002-20120604T122649Z_20110915.nc"

I want to get this :

[1] "D:\/LPRM-AMSR_E_L3_D_SOILM3_V002-20120604T122649Z_20110915.nc"
[2] "D:\/LPRM-AMSR_E_L3_D_SOILM3_V002-20120603T170757Z_20110916.nc"
[3] "D:\/LPRM-AMSR_E_L3_D_SOILM3_V002-20120603T194524Z_20110917.nc"
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
    a<-list.files("D:\semon", "*_20100801.nc", full.names = TRUE)

You want this :

 a<-list.files("D:\semon", "*_[0-9]{8}[.]nc", full.names = TRUE)

or to be match a classic date pattern:

  a<-list.files("D:\semon", "*_\d{4}\d{2}\d{2}[.]nc", full.names = TRUE)

EDIT

The OP is looking to order the output of list.files

   a<-list.files("D:\semon", "*.nc", full.names = TRUE)
   a[order(gsub('.*_(\d{8})[.].*','\1',a))]

For example:

a <- c('D:\AMSER\amser2010+2011/LPRM-AMSR_E_L3_D_SOILM3_V002-20120603T170757Z_20110916.nc',
        "D:\AMSER\amser2010+2011/LPRM-AMSR_E_L3_D_SOILM3_V002-20120603T194524Z_20110917.nc",
        "D:\AMSER\amser2010+2011/LPRM-AMSR_E_L3_D_SOILM3_V002-20120604T122649Z_20110915.nc")

a[order(gsub('.*_(\d{8})[.].*','\1',a))]

[1] "D:\AMSER\amser2010+2011/LPRM-AMSR_E_L3_D_SOILM3_V002-20120604T122649Z_20110915.nc"
[2] "D:\AMSER\amser2010+2011/LPRM-AMSR_E_L3_D_SOILM3_V002-20120603T170757Z_20110916.nc"
[3] "D:\AMSER\amser2010+2011/LPRM-AMSR_E_L3_D_SOILM3_V002-20120603T194524Z_20110917.nc"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...