I have a directory (Windows machine) containing many folders. Iād like to split these folders into batches of three, and move them into separate sub-directories.
ID <- c("a", "b", "c", "d", "e", "f")
group <- c("gp1", "gp1","gp1","gp2","gp2","gp2")
samples <- as.data.frame(cbind(ID,group))
id group
1 a gp1
2 b gp1
3 c gp1
4 d gp2
5 e gp2
6 f gp2
So my working directory contains the folders a-f, and I want to move files a-c into a subdirectory called gp1, and d-f into a subdirectory called gp2. (I actually have over a hundred of these folders, this is just a small example, and each folder contains multiple large files).
This is what I have so far:
# find number of samples
nSamps <- nrow(samples)
# calculate how many groups are required
nGrps <- ceiling(nrow(samples)/3)
# list of batch files we want to create
Batchlist <- 1:nGrps
# create folders with appropriate batch number
for (i in Batchlist){
dir.create(paste("batch",i,sep=""))
}
# assign a group name to each sample
fileList <- rep(Batchlist, each = 3, len = nrow(samples))
# assign each sample a folder name
samples$group <- paste("batch",fileList, sep = "")
This is where I get stuck. I tried writing a loop that moves each folder to the appropriate sub-directory, however it is moving all folders, not in batches (so I'm getting copies of folders a-f in "batch1" and "batch2")
for (j in samples$group){
for (i in samples$ID){
setwd(paste("file/path","/",j,sep = ""))
dir.create(file.path(i))
setwd("../")
file.rename(from = i, to = paste(j,"/", i, sep = ""))
}
}
I've tried a few other things (like writing a small function and using sapply) but the loop is the closest I'm getting.
Can anyone point me in the right direction of where I'm going wrong?