0

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?

jay.sf
  • 60,139
  • 8
  • 53
  • 110

1 Answers1

0

This worked for me. Instead of your last loop, use:

for (i in 1:nrow(samples)){
  dir=which(dir()==samples$group[i])
  dir.create(paste0(dir()[dir],"/",samples$ID[i]))
}

The function dir() returns all existing objects in directory. Match each row to its batch name and create the directory inside of it.

boski
  • 2,437
  • 1
  • 14
  • 30
  • Hi there, thanks for getting back to me! This creates the correct folders but doesn't copy/move them. I tried modifying your code to use file.copy but that just created 3 empty files in each folder. Any ideas? Cheers! – always_stuck Feb 18 '19 at 12:32
  • Gave it a try but to no avail. Check out https://stackoverflow.com/questions/31655076/copy-folders-from-one-directory-to-another-in-r , https://stackoverflow.com/questions/10266963/moving-files-between-folders , problem may be with operating system. – boski Feb 18 '19 at 12:51