user4394417
user4394417

Reputation:

R - load files with condition

I have this simple script for loading files from my computer

files <- "C:/MyDrive/"   
setwd(files )
file_list <- list.files(path=files)

In my drive I have several files

sales_usa.xlsx
clients_usa.xlsx
sales_europe.xlsx
contracts_usa.xlsx
hq_europe.xlsx
usaReport.xlsx
unfinishedusa.xlsx

How to load ONLY files that contains usa in filename? (sales_usa.xlsx, clients_usa.xlsx, contracts_usa.xlsx, usaReport.xlsx, unfinishedusa.xlsx)

Upvotes: 1

Views: 51

Answers (1)

akrun
akrun

Reputation: 887213

We can use pattern in list.files. Here the pattern based on the files showed, 'usa.xlsx', thus we use the regex to .* - characters till usa followed by a dot (. - metacharacter to match any character - so escape \\) and the 'xlsx' at the end ($) of the string

list.files(pattern = ".*usa\\.xlsx$")

Upvotes: 1

Related Questions