Cordyline
Cordyline

Reputation: 15

Change column name with file name of corresponding excel file

I have 100 excel files in one folder and I would like to change the name of the fourth column of each file to corresponding file name in R.

Upvotes: 0

Views: 261

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388982

filenames <- list.files(pattern = '\\.xlsx', full.names = TRUE)

lapply(filenames, function(x) {
  #Read the data
  data <- readxl::read_excel(x)
  #Change the 4th column with filename
  names(data)[4] <- tools::file_path_sans_ext(basename(x))
  #Write the data back
  writexl::write_xlsx(data, x)
})

Upvotes: 1

Related Questions