Search code examples
rrenamefile-rename

Renaming a datafile with a name stored in an object


I have datafile named dat1 I want to rename it to dat2 which I have stored in the object filename.

dat1 <- c(1:5)
filename <- paste("dat2")

If I use,

filename <- dat1

Then the dat1 is renamed to filename and not to dat2.

So how do I rename dat1 with the name stored in the object filename i.e. without mentioning dat2?

I tried using file.rename and mv but unsuccessful.


Solution

  • We can use assign

    assign(filename, dat1)
    dat2
    #[1] 1 2 3 4 5
    

    and now rm the dat1

    rm(dat1)
    

    Or another option is mv from gdata

    library(gdata)
    mv(from = 'dat1', to = filename)
    dat2
    #[1] 1 2 3 4 5
    
    dat1
    

    Error: object 'dat1' not found


    file.rename is used to rename a file name and not the objects in the global environment