Floni
Floni

Reputation: 475

Creating files from a list of csv in a directory

I have the folder "TEST AIS Florent/test division/division2014/testexport/testloop" with 4 csv files in it: testexport_1; testexport_2; testexport_3 and testexport_4.

I would like to filter each file and export them to different csv: one for testexport_1, a second one for testexport_2, etc.

For now, my script is

rm(list = ls())
setwd("D:/TEST AIS Florent/test division/division2014/testexport/testloop")
fileList <- list.files(pattern="testexport_.*\\.csv", recursive=TRUE)
#lenghtlist<-as.numeric(length(fileList))

for (file in fileList) {

data2014<-read.table(file, header=F, fill=T, quote="\"", na.strings=c(""," ", "null", "NA"), sep=",") 

#########filtering the data here

write.csv(data2014,   file = "data.csv",sep = ";", quote= F, col.names=T, row.names=F)
} 

The problem is when I write the csv in my working directory, R is only creating one output file data.csv and is writting over and over this file.

I would like to have for testexport_1 --> the output data_1 and for testexport_2 --> the output data_2, etc.

Thank you!

Upvotes: 2

Views: 95

Answers (1)

Roman Luštrik
Roman Luštrik

Reputation: 70653

Construct the file string on the fly by replacing main part of the string with "data".

...
write.csv(data2014,   file = gsub("testexport", "data", file),sep = ";", quote= F, col.names=T, row.names=F)
...

Upvotes: 4

Related Questions