1

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...

M--
  • 25,431
  • 8
  • 61
  • 93
holastello
  • 593
  • 1
  • 7
  • 16
  • `file.rename(list.files(), paste(list.files(), "foo", sep="_"))` – M-- Jul 17 '17 at 18:13
  • Please read [How to make a great reproducible example in R?](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). This may help you to improve your question. – M-- Jul 17 '17 at 19:09

2 Answers2

1

The problem with your solution is as.data.frame; file.rename() gets lists as inputs.

You can simply do it like this:

file.rename(list.files(), paste(list.files(), "foo", sep="_")) 

But problem with doing so is that you make the extension of files to be altered. Above would change mycode.r to mycode.r_foo which then cannot be opened by R.

M--
  • 25,431
  • 8
  • 61
  • 93
  • The changes that I'm making to the filenames are actually much more complicated (and also don't result in altering the file extension - sorry for the silly example), so this solution doesn't really work for me. Furthermore, I'm only trying to change a subset of all the files in the directory, so putting `list.files()` doesn't work. I'll make some edits to my question to clarify. – holastello Jul 17 '17 at 18:44
1

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))
Prem
  • 11,775
  • 1
  • 19
  • 33