Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using list.files() in R to find files that start with a specific string

Tags:

file

list

r

I am using list.files() in r to read in files. However, the pattern= input will scan all files that contain that special string I am scanning for...

Ex.

MASTERLIST =list.files("/Volumes/3TB/",pattern="CL")

will call in the following files:

[1] "CLF16"  "CLF17"  "CLF18"  "CLF19"  "CLG16"  "CLG17"  "CLG18"  "CLH16"  "CLH17"  "CLJ16"  "CLJ17"  "CLK16"  "CLK17"  "CLK18"  "CLM16"  "CLM17" 
[17] "CLM18"  "CLM19"  "CLN16"  "CLN17"  "CLQ16"  "CLQ17"  "CLU15"  "CLU16"  "CLU17"  "CLV15"  "CLV16"  "CLV17"  "CLX15"  "CLX16"  "CLX17"  "CLZ15" 
[33] "CLZ16"  "CLZ17"  "CLZ18"  "CLZ19"  "CLZ20"  "MCLH16" "MCLM16" "MCLU16" "MCLZ16"

But I only want those files that begin with CL and not every file that contains CL like files 38 through 41

How do I get it to call only those files that begin that pattern?

like image 767
Rime Avatar asked May 03 '16 08:05

Rime


People also ask

How do I get a list of filenames in R?

To list all files in a directory in R programming language we use list. files(). This function produces a list containing the names of files in the named directory. It returns a character vector containing the names of the files in the specified directories.

What are list files R?

You can use the list. files() function in R to list out every file in a specific folder.


2 Answers

The pattern argument takes a regex, so you can use: pattern = "^CL"

like image 180
sebastian-c Avatar answered Oct 03 '22 20:10

sebastian-c


You can use Sys.glob to use wildcard expansion and so to precise what you want:

Sys.glob('CL*')

should do the job you want.

like image 25
ClementWalter Avatar answered Oct 03 '22 20:10

ClementWalter