NAmo
NAmo

Reputation: 55

Batch rename list of files to totally different names using R

I have 330 files that i would like to rename using R. I saved the original names and the new names in a .csv file. I used a script which does not give an error but it does not change the names.

Here is a sample of the new names:(df1)

D:\Modis_EVI\Original\EVI_Smoothed\ MODIS_EVI_20010101.tif
D:\Modis_EVI\Original\EVI_Smoothed\ MODIS_EVI_20010117.tif
D:\Modis_EVI\Original\EVI_Smoothed\ MODIS_EVI_20010201.tif

And a sample of the original names:(df2)

D:\Modis_EVI\Original\EVI_Smoothed\ MODIS.2001001.yL1600.EVI.tif
D:\Modis_EVI\Original\EVI_Smoothed\ MODIS.2001033.yL1600.EVI.tif
D:\Modis_EVI\Original\EVI_Smoothed\ MODIS.2001049.yL1600.EVI.tif

Then here is the script i'm using:

csv_dir   <-  "D:\\"
df1        <- read.csv(paste(csv_dir,"New_names.csv",sep=""), header=TRUE, sep=",")        # read csv
hdfs       <- df1$x                                 
hdfs       <- as.vector(hdfs)                                  
df2        <- read.csv(paste(csv_dir,"smoothed.csv",sep=""), header=TRUE, sep=",")        # read csv
tifs       <- df2$x                                 
tifs       <- as.vector(tifs)                       
for (i in 1:length(hdfs)){ 
  setwd("D:\\Modis_EVI\\Original\\EVI_Smoothed\\")
  file.rename(from =tifs[i], to = hdfs[i]) 
}

Any advice please?

Upvotes: 1

Views: 1515

Answers (1)

Robert Hijmans
Robert Hijmans

Reputation: 47101

I think you mix up the old and the new files, and you are trying to use rename the new file (names), which do not exist, to the old file names. This might work

file.rename(from =hdfs[i], to = tifs[i]) 

A general approach would go like this:

setwd("D:\\Modis_EVI\\Original\\EVI_Smoothed\\")

fin <- list.files(pattern='tif$')
fout <- gsub("_EVI_", ".", fin)
fout <- gsub(".tif", "yL1600.EVI.tif", fout)

for (i in 1:length(fin)){ 
   file.rename(from=fin[i], to= fout[i]) 
}

To fix your script (do you really need .csv files?)

setwd("D:\\Modis_EVI\\Original\\EVI_Smoothed\\")

froms  <- read.csv("d:/New_names.csv", stringsAsFactors=FALSE)
froms <- as.vector(froms$x) 

First check if they exist:

all(file.exists(froms))

Perhaps you need to trim the names (remove whitespace) -- that is what the examples you give suggest

library(raster)
froms <- trim(froms) 
all(file.exists(froms))

If they exist

tos  <- read.csv("d:/smoothed.csv", stringsAsFactors=FALSE)
tos <- as.vector(tos$x)                       
# tos <- trim(tos)

for (i in 1:length(froms)) { 
  file.rename(froms[i], tos[i]) 
}

Upvotes: 1

Related Questions