user1977802
user1977802

Reputation: 353

Subsetting Images into Separate Folders in R

I have a folder with several thousand files inside. I want to subset all of these files into individual subfolders, each with 15 files (doesnt matter which files go where or subfolder names). Basically, I need to process these files in a program and I would like to break them down into folders with a smaller, more manageable number of files inside.

Upvotes: 0

Views: 183

Answers (1)

G5W
G5W

Reputation: 37661

You need several functions to do this.

list.files to get all of the file names

dir.create to create the directories and

file.rename to move the files

AllFiles = list.files("TheFolder")

## Make all of the folders
FolderNumber = floor(1:length(AllFiles)/15) + 1
FolderName = sprintf("Folder%03d", FolderNumber)
for(f in unique(FolderName)) { dir.create(f) }

## Move the files
for(i in 1:length(AllFiles)) {
    file.rename(paste("TheFolder", AllFiles[i], sep="/"),
        paste(FolderName[i], AllFiles[i], sep="/"))
}

If you want to be cautious, you might use file.copy instead of file.rename. This will make a copy to the folders without deleting the original, so that you can check that everything is OK before deleting.

Upvotes: 1

Related Questions