How to create a series of folders (0-48) and move files to corresponding new folder R

46 Views Asked by At

I need to make a series of folder labelled ppt-01:ppt-48. I then need to move all of the corresponding participant files into the new folders.

Currently all files (10 per ppt) are in one folder, and somewhere in each file name the ppt number is included.. e.g. XX01_040_xxx6_9 Where the 040 relates to ppt number.

I first tried to create a list of folder names using a for loop, but I could not figure out how to save the output

setwd("P:/data")

for (i in 1:48){
  print(paste0("ppt-0", i))
}

**So i used lapply **

x = (1:48)
fun <- function(x){
  paste0("ppt-0", x)
}

output <- lapply(x, fun)
output

path <- "data"

dir.create(output)

I then intend to try to list.files and then use a for loop or lapply / or maybe an if statement to move the files into their corresponding folders, but I'm not quite sure how to approach this.

This does not work and I'm not sure what else to try - any help would be very appreciated.

1

There are 1 best solutions below

6
Mohamed Desouky On

You can use this for creating the folders

for (i in 1:48){
    if(i < 10)
    dir.create(paste0("ppt-0", i))
    else dir.create(paste0("ppt-", i))
}

Then to move the files

for (f in list.files("path to your files")){
    n <- gsub('^_0(\\d+)_', '\\1', stringr::str_extract(f, '_\\d+_'))
    to <- paste0("ppt-0", n)
    file.copy(from = paste0('path to your files', f),
              to   = paste0('path to your folder data', to))
}