rename multiple files in a folder using R [duplica

2019-08-03 20:02发布

问题:

This question already has an answer here:

  • How do I rename files using R? 2 answers

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!

回答1:

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))
 })


标签: r file rename