read.xlsx 'Error in loadWorkbook(file): Cannot find file' R

nchimato picture nchimato · Sep 15, 2015 · Viewed 13.4k times · Source

I am trying to read in a number of Excel files into R using read.xlsx using the xlsx package but when I do so I am getting the following error:

Error in loadWorkbook(file) : Cannot find id100.xlsx

First I list the files in the directory:

> files <- list.files(datDir, pattern = ".xlsx")

Then I use read.xlsx to read them all in:

 for (i in seq_along(files)) {
    assign(paste("id", i, sep = "."), read.xlsx(files[i],1,as.data.frame=TRUE, 
    header=FALSE, stringsAsFactors=FALSE, na.strings=" "))
 }

I checked to see if the file was even in the list and it is:

> files
  [1] "id100.xlsx" "id101.xlsx" etc...

> files[1]
  [1] "id100.xlsx"

I have used this code many times before today and for some reason it is just not working. I keep getting that error. Does anyone have any suggestions?

Thanks!

Answer

vck picture vck · Sep 15, 2015

If your working directory is different from datDir you should use full.names=T like this:

files <- list.files(datDir, pattern = ".xlsx",full.names=T)