Smajl
Smajl

Reputation: 8015

R read all files in a directory

I am trying to read and merge together all the csv files in a directory. I found this excellent SO answer: Importing multiple .csv files into R but it doesn't seem to work for me.

I am able to list the files (they are in my home directory in a sub-folder called "test"):

library(data.table)  
files <- list.files(path = "test",pattern = ".csv")
print(files)

This correctly prints the content of the directory.

When I try to load them using

temp <- lapply(files, fread, sep=",")
data <- rbindlist(temp)

I get File 'xyz.csv' does not exist. Include one or more spaces to consider the input a system command.

Do I have to somehow specify the path again? I fought that this information is already contained in the file object. Thanks for any help!

Upvotes: 5

Views: 7896

Answers (1)

jamieRowen
jamieRowen

Reputation: 1549

I suspect the problem lies in the path to the files. Most likely because your working directory is one level up from the directory "test". Try:

    list.files(path = "test", pattern = ".csv", full.names = TRUE)

The full.names argument will include the path to the files in it's output.

Upvotes: 13

Related Questions