Opening files from working directory

1.3k views Asked by At

I have the following issue. I have imported multiple csv files into my working directory. Would appreciate any help

files
[1] "sept2010.csv__001.csv" "sept2010.csv__002.csv" "sept2010.csv__003.csv" "sept2010.csv__004.csv""sept2010.csv__005.csv" "sept2010.csv__006.csv"

Here I have more than 200 csv files. If I wand to open the files I can do it with

data<-rbind(sept2010.csv__001.csv,sept2010.csv__002.csv) # It is time consuming to rbing 200 files.

When I try to open the files with :

myfiles = do.call(rbind, lapply(files, function(x) read.csv(x, stringsAsFactors = FALSE)))

I got an error message:

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

When I try the following:

 data<-do.call("rbind", lapply(files, read.csv, header = TRUE))

I get the same error message

If I try to open the files manually with:

folder <- "C:/Users/NewPap/Desktop/DATA/test"     
file_list <- list.files(path=folder, pattern="*.csv")
for (i in 1:length(file_list)){
  assign(file_list[i], 
     read.csv((paste(folder, file_list[i], sep='')))
   )}

I get the same error

I am not sure what did I do wrong. Would appreciate any help

2

There are 2 answers

6
xraynaud On BEST ANSWER

If all your files are in your working directory, then

lapply(grep(".csv",list.files(full.names=T),value="TRUE"),read.csv)

should open all the CSV files in a list (each file content will be in an element of the list).

If all CSV files have the same number of column, then

do.call("rbind",lapply(grep("csv",list.files(full.names=T),value="TRUE"),read.csv)) 

will produce a single dataframe with all CVS files.

1
tushaR On
folder <- "C:/Users/NewPap/Desktop/DATA/test"     
files <- list.files(path=folder, pattern="*.csv")

Try this:

data = Map(f = read.csv,files,header=T)
Reduce(function(x,y){rbind(x,y)},data)