Duck
Duck

Reputation: 39595

Read multiples files in R allocated in different directories but with the same name

I am trying to solve a little problem in R about reading multiples files with the same name but allocated in different directories.

I have 100 files named R04 and with extension .xlsx, but they are allocated in 100 different directories, like this:

file 1: C:\General Data\Month1\R04.xlsx

file 2: C:\General Data\Month2\R04.xlsx

.

.

.

file 100: C:\General Data\Month2\R04.xlsx

My problem is I can't get to read these files. Maybe it is possible to read they with for, and due to the same name in 100 files I don't know if is possible to name each one with a number related to the month, for example in the case of first file the name should be 01 due to month 1, etc.

Upvotes: 0

Views: 146

Answers (2)

agstudy
agstudy

Reputation: 121568

I would use list.files to list my files by pattern. Then some regular expression to name my files.

For example:

library(XLConnect)
files.path <- list.files(pattern=".*R04.xlsx",full.names=TRUE)
setNames(lapply(files.path, function(x) read.xlsx(x,1)),
         gsub('.*/(.*)/R04.*','\\1_R04',files.path))

Using some data to show how I am using gsub here:

ll <- c("C:/General Data/Month1/R04.xlsx",
         "C:/General Data/Month2/R04.xlsx",
         "C:/General Data/Month3/R04.xlsx")
gsub('.*/(.*)/R04.*','\\1_R04',ll)
[1] "Month1_R04" "Month2_R04" "Month3_R04"

Upvotes: 1

Metrics
Metrics

Reputation: 15458

Try using the XLConnect package.

library(XLConnect)
file1 <- readWorksheet(loadWorkbook("C:\General Data\Month1\R04.xlsx"),sheet=1)

Upvotes: 0

Related Questions