Alejandro Bernal
Alejandro Bernal

Reputation: 11

Rename dates files with R

I have named each file for each day of the years between 2012 and 2016 like this: 2012-01-01.csv; 2012-01-02.csv... until 2016-12-31.csv. But for 2017 and 2018 the files are named like this: 20170101.csv; 20170102.csv... Could someone help me include the hyphens in the second files so that they have the same name as the first ones?

Thanks!

Upvotes: 1

Views: 201

Answers (2)

Daniel O
Daniel O

Reputation: 4358

Edit: use this instead

setwd("C:\\Users\\...Path to your data")

DataFileNames <- list.files(pattern="\\.csv$")
sub("(\\d{4})(\\d{2})(\\d{2})(.*)","\\1-\\2-\\3\\4",DataFileNames)
file.rename(DataFileNames,NewDataFileNames)

Old answer:

Theres a lot of missing information from your question, but you should be able to adjust the code below to suit your needs.Mostly, you'll need to edit the read.csv line if you have headers and adjust other parameters.

Note: This will overwrite all your tables, so make sure the data is imported properly with the read.csv in the lapply before you run the write.csv (last line)

setwd("C:\\Users\\...Path to your data")

DataFileNames <- list.files(pattern="\\.csv$")
Datafiles <- lapply(DataFileNames, read.csv, header=FALSE)

DataFileNames <- sub("(\\d{4})(\\d{2})(\\d{2}).csv","\\1-\\2-\\3",DataFileNames)
lapply(1:length(Datafiles), function(x) write.csv(Datafiles[x], DataFileNames[x]))

Upvotes: 1

ThomasIsCoding
ThomasIsCoding

Reputation: 101818

Maybe you can try the following code with list.files + file.rename

old <- list.files(pattern = ".*.csv")
new <- paste0(as.Date(gsub(".csv","",old,fixed = TRUE),format = c("%Y-%m-%d","%Y%m%d")),".csv")
file.rename(old,new)

Upvotes: 1

Related Questions