6

I am trying to rename several files using R, and I have tried every solution I was able to find to similar questions without success.

I have created a vector with the names of the files I want to change, and another one with the names I want to change them to, so they'll look something like:

from1 <- as.character(c("test1.txt", "test2.txt", "test3.txt")) to1 <- as.character(c("testA.txt", "testB.txt", "testC.txt")) 

where from1 corresponds to the names of the existing files in my working directory, and to1 corresponds to the names I want them to have. When I try file.rename(from1, to1) I get [1] FALSE FALSE FALSE and even if I try it with just one element of the vector as in file.rename(from1[1], to1[1])I just get [1] FALSE and nothing happens in my folder

I have also tried this function posted as an answer to a question very similar to mine, and it seems to work, because when I run a test I get

found 1 possible files would change test1.txt to testA.txt changed 0 

but when I actually try to do it I get

found 1 possible files changed 1 

but nothing has actually changed in my directory.

I am not sure if this question is clear enough or more code is needed, if so please ask and I'll be happy to edit.

3
  • the code works for me.Are you sure that you are in the directory of the files ? Use getwd() and setwd() Commented Nov 13, 2015 at 11:46
  • also, no need for the as.character as the " " already defines a character. Commented Nov 13, 2015 at 11:46
  • 1
    Possible duplicate of How to rename files with a specific pattern in R? Commented Nov 19, 2016 at 13:58

2 Answers 2

8

Given that you are in the right working directory (otherwise set it with setwd(""), you can change file names with:

from1 <- c("test_file.csv", "plot1.svg") to1 <- c("test.csv", "plot.svg") file.rename(from1, to1) 

But make sure that you are in the right directory and that the files exist (which you can do with list.files or file.exists.

Sign up to request clarification or add additional context in comments.

Comments

1

To rename a file in R, simply use:

file.rename("mytest.R", "mytest2.R") 

This command can also be vectorized.

files.org = c("mytest1.R","mylife.R") files.new = c("mytest01.R","mytest02.R") file.rename(files.org, files.new) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.