2

I want to write a simple loop that will create copies of all of the images in a folder (.jpg) and sort them into different folders according to the values in a table.

For example if I had three images and wanted to move them into folders according to this table: enter image description here

I can read in the files using

files <- list.files(dir, pattern="*.JPG", full.names=TRUE, recursive=FALSE)

but I could use some help coding the loop that will use a conditional statement to create copies of the files in new folders using the appropriate string from the 'destination' column, which corresponds to the factor 'group'.

This is similar to this question and this question but different in that I want to copy images and rename them based on the values in the table rather than cycle through multiple tables.

Thank you in advance!!

Kartograaf
  • 143
  • 6
  • 5
    See `?file.copy`. Build the full or relative paths to your destinations and `file.copy(from = data$name, to = data$destination)`. No loop needed. Not sure what conditional statement you think is needed. – Gregor Thomas Mar 10 '20 at 19:23

1 Answers1

0

Many thanks to @Gregor Thomas, this is what I came up with:

dir <- "C:/path"

setwd(dir)
data <- read.csv("key.csv")

subfolder_names <- data$destination
for (j in 1:length(subfolder_names)){
  folder<-dir.create(paste0(dir,subfolder_names[j]))
}

files <- list.files(dir, pattern="*.JPG", full.names=TRUE, recursive=FALSE)

file.copy(from = file.path(files), to = file.path(data$destination, data$name))
Kartograaf
  • 143
  • 6