Search code examples
rfilefile-rename

How to rename files using R?


I have a bunch of files that have "_001" in their file names. I followed a script posted online and I am at the directory where all my files are located:

filez <- list.files()
sapply(filez, function(X) {file.rename(from=x, to=sub(pattern="_001", replacement="", x))})

But I keep getting this error message:

Error in file.rename(from = x, to = sub(pattern = "001", replacement = "")) : object 'x' not found".

Can anyone help me solve this problem?


Solution

  • I don't think you need to do this with sapply at all. (This will bypass the problem you are having where the arguments to file.rename and sub should have been X.) Try this instead:

    filez <- list.files()
    file.rename(from=filez, to=sub(pattern="_001", replacement="", filez))