msh855
msh855

Reputation: 1571

Extract part of a string from a filename

I am importing multiple excel file and I want to create a vector with the names of each file, which I then want to use to perform some further operations.

Here is a minimum working example, assuming that I am importing two excel files:

Excel file name 1: x1_company_90.xls
Excel file name 2: gghi_company_90.xls

I want to create a vector with the following parts of the file names once I read them in r:

expected result:

names<-c ("x1","gghi")

Upvotes: 2

Views: 2004

Answers (1)

zx8754
zx8754

Reputation: 56219

Using gsub:

myFileNames <- list.files(path = "my/path", pattern = "*_company_90.xls")

# example file list:
# myFileNames <- c("x1_company_90.xls","gghi_company_90.xls")

myNames <- gsub("_company_90.xls", "", myFileNames, fixed = TRUE)
myNames
# [1] "x1"   "gghi"

Upvotes: 1

Related Questions