Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add a new line in multiple existing csv files using R?

I want to read multiple csv files into R, but the csv files don’t en with a new line.
When I try to read csv files i get this error message "Files must end with a newline" so in order to fix that for one single csv file this code which works fine:

# Add blank row
blank <- ""

# csv file name
csv_name <- "testfile.csv"

# writing row in the csv file
write.table(blank, file = csv_name, sep = ";",
            append = TRUE, quote = FALSE,
            col.names = FALSE, row.names = FALSE)

But I don’t know how to scale this when I have multiple csv files (in the same folder) and all the files have the same problem: they don’t end with a new line. I have tried but failed to find a good way to write a loop or to use purrr map functions. A suggestion would be much appreciated!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If you really want to use R for this task, you could use

my_path <- "."

my_csv_list <- list.files(path = my_path, pattern = ".csv$")

blank <- ""

for (file in my_csv_list) {
  write.table(blank, file = file, sep = ";",
              append = TRUE, quote = FALSE,
              col.names = FALSE, row.names = FALSE)
}

or instead of a for-loop

sapply(my_csv_list, 
       function(file) 
         write.table(blank, file = file, sep = ";",
                     append = TRUE, quote = FALSE,
                     col.names = FALSE, row.names = FALSE))

Just set my_path to the path containing your .csv-files. file.path could be useful for this.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading