3

I have a folder which contains several files named by the date the data was measured. For example: "07182014.csv","07192014.csv"...

Since I have multiple stations for the measurements, I would like to add the station number before each file name for distinguish purposes. For example, the file "07182014.csv" will become "N1_07182014.csv".

I'm new to R, and most of the time I search the web for solutions to my data analysis problem.

Can someone help me revise the code I'm having below so I can properly rename all files in the folder? Or if any other better solution can be provided, that will be helpful!

setwd("C:\\data")
files <- list.files() 
sapply(files,FUN=function(eachPath){ 
file.rename(from=eachPath,to=sub(pattern="[$.csv]", paste0("N0_"),eachPath)) 
}) 

Thanks a lot!

Mahdi Jadaliha
  • 1,947
  • 1
  • 14
  • 22
Vicki1227
  • 489
  • 4
  • 6
  • 19

1 Answers1

4

Here is my answer:

folder = "C:\\data"
files <- list.files(folder,pattern = "*.CSV",full.names = T) 
   sapply(files,FUN=function(eachPath){ 
   file.rename(from=eachPath,to= sub(pattern="\\/", paste0("\\/N0_"),eachPath))
 })
Mahdi Jadaliha
  • 1,947
  • 1
  • 14
  • 22