Ariel
Ariel

Reputation: 153

How to read csv inside a folder in R?

I am working in a directory, but the data I want to read is in a subdirectory. I get an error when I try to read the csv files, my code is the following:

setwd("~/Documents/")
files <- list.files(path = "data/")
f <- list()
for (i in 1:length(files)) {
  f[[i]] <- read.csv(files[i], header = T, sep = ";")
}

And the error I get is:

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

What am I doing wrong?

Upvotes: 1

Views: 19795

Answers (1)

Michael Kirchner
Michael Kirchner

Reputation: 889

The following will work, assuming you have correctly specified the other read.csv parameters.

setwd("~/Documents/")
files <- list.files(path = "data/")
f <- list()
for (i in 1:length(files)) {
  f[[i]] <- read.csv(paste0("data/",files[i]), header = T, sep = ";")
}

Alternatively, you could drop the paste0 and simply set your working directory to ~/Documents/data/ in the first place.

setwd("~/Documents/data/")
files <- list.files() #No parameter necessary now since you're in the proper directory
f <- list()
for (i in 1:length(files)) {
  f[[i]] <- read.csv(files[i], header = T, sep = ";")
}

If you need to be in ~/Documents/ at the end of this loop, then finish it up by adding the following after the loop.

setwd("~/Documents/")

Upvotes: 3

Related Questions