Search code examples
rregexdataframevectorbatch-rename

Batch renaming files in R


I have a directory with thousands of files, and I would like to rename a subset of these files.

Here's a highly simplified example of what I'm trying to do:

    library(dplyr)    
    f <- as.data.frame(list.files(), header=FALSE)
    colnames(f) <- 'origFilename'
    f2 <- f %>% separate(origFilename, into=c('ID','date','channel','position','extension'), sep='_', remove=FALSE) 
        %>% filter(ID > 10)
    f2$ID <- as.numeric(f2$ID)
    f3 <- f2 %>% mutate(newID = ID + 1)
    f3$newFilename <- paste(f3$newID, f3$date, f3$channel, f3$position, 
    f3$extension, sep='_')
    f3$origFilename <- paste(f3$ID, f3$date, f3$channel, f3$position, f3$extension, sep='_')
    file.rename(f3$origFilename, f3$newFilename)

The last line of this code gives the following error:

Error in file.rename(f$files.old, f$files.new) : invalid 'from' argument

Any ideas on how to fix this? Sorry, I'm not sure how to make a fully reproducible example here...


Solution

  • Are you looking for something like this?

    f <- as.data.frame(list.files(), header=FALSE)
    colnames(f) <- 'files.old'
    #"foo" will be added just before the extension
    f$files.new <- sapply(f$files.old,function(x) gsub("^[^.]*.",paste(gsub(".[^.]*$", "", x), 'foo.', sep='_'),x))
    file.rename(as.vector(f$files.old), as.vector(f$files.new))