Search code examples
robjectnaming

retrieve original file name of loaded data object in R


I'm trying to retrieve the original filename of an object stored in R. The reason is because after making modifications to the data object, I want to save the new object using the same prefix in filename. Here is what I mean:

dat <- read.csv("../DATA/Cats.2017.csv")

Do a bunch of analyses on dat to make dat.new and save the file using the original prefix:

write.csv(dat.new, file="../DATA/Cats.2017.NEW.csv"

I'm trying to avoid manually changing the filename every time I load another csv file. I hope that makes sense and there is an easy solution!


Solution

  • The fastest way to do this is likely using gsub().

    fileName <- '../DATA/Cats.2017.csv'
    dat <- read.csv(fileName)
    write.csv(dat, paste0(gsub('.csv', '.NEW.csv', fileName)))
    

    Here are the rbenchmark results, although I do want to point out that the computational time between these three methods are almost negligible if you're running this code less than 1,000 times.

    fileName <- "../DATA/Cats.2017.csv"
    rbenchmark::benchmark(
      'str_sub' = {
        newName <- paste0(stringr::str_sub(fileName, 1, -4), "NEW.csv")
      },
      'stringi' = {
        newName <- paste0(paste(unlist(stringi::stri_split_fixed(basename(fileName), ".", n = 3))[-3], collapse = "."), ".NEW.csv")
      },
      'gsub' = {
        newName <- paste0(gsub('.csv', '.NEW.csv', fileName))
      },
      replications = 100000
    )
    
         test replications elapsed relative user.self sys.self user.child sys.child
    3    gsub       100000    0.81    1.000      0.82        0         NA        NA
    1 str_sub       100000    1.10    1.358      1.10        0         NA        NA
    2 stringi       100000    1.67    2.062      1.67        0         NA        NA