GregdeLima
GregdeLima

Reputation: 404

Opening Excel file and Saving as CSV in R

I'm using the following code:

setwd("~/R/Test")
require(openxlsx)
file_list <- list.files(getwd())

for (file in file_list){
  file = read.xlsx(file)
  write.csv(file,file=file)
}

Where it opens each file in a directory, reads the excel file, and saves as a CSV. However, I'm trying to source the original file name, and save the CSV with the original file name. Is there a way to do this?

Thanks!

Upvotes: 0

Views: 2228

Answers (1)

blakeoft
blakeoft

Reputation: 2400

As pointed out in the comments, you're overwriting the variable file. I also recommend changing the extension of the file. Try this as your for loop:

for (file in file_list) {
  file.xl <- read.xlsx(file)
  write.csv(file.xl, file = sub("xlsx$", "csv", file))
}

Note that you'll need to change the "xlsx$" to "xls$" depending on what the extensions are of the files in your directory.

Upvotes: 1

Related Questions