R: How to select files in directory which satisfy conditions both on the beginning and end of name?

心已入冬 提交于 2021-02-07 02:30:52

问题


I need to select files which start with "M" and end with ".csv". I can easily select files which start with "M" : list.files(pattern="^M"), or files which end with "csv": list.files(pattern = ".csv"). But how to select files which satisfy both conditions at the same time?


回答1:


You could try glob2rx

lf <- list.files("path_to_directory/", pattern=glob2rx("M*.csv"))

which translates to:

glob2rx("M*.csv")
[1] "^M.*\\.csv$"



回答2:


The pattern argument takes a regular expression:

list.files(pattern='^M.*csv')

To be more specific, your second expression:

list.files(pattern='.csv')

Is matching all files with the string csv preceded by any character. To be explicit and only match files with a .csv extension:

list.files(pattern='\\.csv$')


来源:https://stackoverflow.com/questions/21585413/r-how-to-select-files-in-directory-which-satisfy-conditions-both-on-the-beginni

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!