Probably a pretty simple answer but I've had trouble converting a bunch of .txt files to .csv files in a loop. I don't want to merge or append them, just convert 71 individual .txt files into 71 individual .csv files.
I was doing my best to refer to other questions with my code relying on this thread: create a loop: convert .txt to .csv in R
I was adapting it and this is what I have so far:
filelist = list.files(pattern = ".txt")
for (i in 1:length(filelist)) {
cur.input.file <- filelist[i]
cur.output.file <- paste0(cur.input.file, ".csv")
print(paste("Processing the file:", cur.input.file))
# If the input file has less than 11 rows you will reveive the error message:
# "Error in read.table: no lines available in input")
data = read.delim(cur.input.file, header = TRUE)
write.table(data, file=cur.output.file, sep=",", col.names=TRUE, row.names=FALSE)
}
However, my results are coming out with:
[1] "Processing the file: filename1.txt.txt"
[1] "Processing the file: filename2.txt.txt"
[1] "Processing the file: filename3.txt.txt"
[1] "Processing the file: filename4.txt.txt"
[1] "Processing the file: filename5.txt.txt"
and the formatting is all screwed up.
Any advice/ what am I doing wrong?
Cheers and Thank you.
This is a basic solution:
You can always add parameters in the read.table and write.csv functions per your requirements.
Edited written file name per Gregor's comment