KNN
KNN

Reputation: 535

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!

Upvotes: 1

Views: 511

Answers (3)

slava-kohut
slava-kohut

Reputation: 4233

You can try something like this:

file_path <- "path/to/my/file/tmm/1.file.csv"
file_name <- basename(file_path)

sp <- unlist(strsplit(file_name, '\\.'))
file_prefix <- paste0(sp[-length(sp)], collapse = '.')
new_file_name <- paste0(file_prefix, ".NEW.csv")

Upvotes: 3

Benjamin Ye
Benjamin Ye

Reputation: 518

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

Upvotes: 1

Brian
Brian

Reputation: 8275

The easiest way is probably something like:

orig_name <- "../DATA/Cats.2017.csv"

dat <- read.csv(orig_name)

# your analysis here

new_name <- paste0(stringr::str_sub(basename(orig_name), 1, -4), ".NEW.csv")

write.csv(dat.new, new_name)

Upvotes: 1

Related Questions