Getting error in file(file, "rt"): cannot open the connection

an2825 picture an2825 · Mar 4, 2018 · Viewed 18k times · Source

I am running the following code...

#Create a list of all the files
file.list <- list.files(path="~/R/natural-language-processing/class-notes", pattern=".csv")

#Loop over file list importing them and binding them together
D1 <- do.call("rbind",lapply(file.list, read.csv, header = TRUE, stringsAsFactors = FALSE))

This is the error I get when I run do.call line above.

Error in file(file, "rt") : cannot open the connection

I've tried resetting my wd. My current getwd() is

~/R/natural-language-processing

I've looked through the other

Error in file(file, “rt”): cannot open connection

Answer

Richard Border picture Richard Border · Mar 4, 2018

Most likely you are trying to open files from the working directory instead of the directory in which you called list.files. Instead try

D1 <- do.call("rbind",
              lapply(paste0("~/R/natural-language-processing/class-notes/",
                            file.list),
                     read.csv, header = TRUE, stringsAsFactors = FALSE))

Alternatively, you can set the full.names argument to TRUE in list.files to get complete paths:

file.list <- list.files(path="~/R/natural-language-processing/class-notes", 
                        pattern=".csv", full.names = TRUE)