Reputation: 3941
I have a folder of photographs I'd like to rename. The photos are stored in several sub-folders, and I would like to rename the photographs to include the appropriate meta data in the file name using R.
If I create a list of file names using:
LF<-list.files(recursive=TRUE)
I get something like this:
[1] "1-South/L14_4848.jpg" "1-South/L14_4849.jpg" "1-South/L14_4850.jpg"
[4] "1-South/L14_4851.jpg" "1-South/L14_4852.jpg" "2-North/L14_4854.jpg"
[7] "2-North/L14_4855.jpg" "2-North/L14_4856.jpg" "2-North/L14_4857.jpg"
[10] "2-North/L14_4858.jpg" "3-East/L14_4860.jpg" "3-East/L14_4861.jpg"
I have a separate data frame that contains the appropriate metadata for each of these files. The data frame includes a matching photo name (in this case the files beginning with "L")
Date<-"2014-04-28"
Location<-"ALK"
Site<-"PR2"
Habitat<-"Forest"
Quad<-1:12
Photo<-c("L14_4848.jpg","L14_4849.jpg","L14_4850.jpg","L14_4851.jpg","L14_4852.jpg","L14_4854.jpg","L14_4855.jpg","L14_4856.jpg","L14_4857.jpg","L14_4858.jpg","L14_4860.jpg","L14_4861.jpg")
Meta<-data.frame(Date,Location,Site,Habitat,Quad,Photo)
How can I rename the photo files in my various sub-directories to include the meta data as found in the "Meta" data frame. Ideally a finished file name for a photo would look like this
Location_Site_Habitat_Quad_Date_Photo
or
ALK_PR2_Forest_1_2014-04-28_L14_4848.jpg
Upvotes: 0
Views: 700
Reputation: 54237
Try this, but do a backup before:
LF <- LF[order(match(basename(LF), Meta$Photo))] # reorder if necessary
Meta <- Meta[, c("Location", "Site", "Habitat", "Quad", "Date", "Photo")] # col order
fn <- apply(Meta, 1, function(row) paste0(row, collapse = "_"))
file.rename(LF, file.path(dirname(LF), fn))
Upvotes: 1