使用R重命名文件夹中的多个文件 [英] rename multiple files in a folder using R
问题描述
我有一个文件夹,其中包含几个文件,这些文件以测量数据的日期命名.例如:"07182014.csv","07192014.csv" ...
I have a folder which contains several files named by the date the data was measured. For example: "07182014.csv","07192014.csv"...
由于我有多个测量站,因此我想在每个文件名之前添加站号,以用于区分目的.例如,文件"07182014.csv"将变为"N1_07182014.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".
我是R的新手,在大多数情况下,我都是在网络上搜索我的数据分析问题的解决方案.
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))
})
非常感谢!
推荐答案
这是我的答案:
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重命名文件夹中的多个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!