简体   繁体   中英

Is there an R function/loop that can add a unique number or string to a filename?

I am new to R and Stack Overflow. I have looked extensively for an answer to my question, and I don't believe this is a repeat question.

I have.csv files that are loaded into my script as data frames, and I need those data frames saved as.Rda or.RDS files.

The way I have the code written, the old.Rda files will get overwritten in the directory I have them saving to.

base::save(data, file="data.Rda")

Is there a way to create a loop that attaches some random number or string onto a pre-existing file name when it is save, or even a function that generates a unique ID #? What I am looking for is an output that looks like

data_1.Rda data_2.Rda data_3.Rda and so on where the _# is randomly generated every time I run the code.

I have tried to create a vector such as

x<-c(a, b, c, d, e, f, g, h, i, j, k)

then created a loop to save through each individual variable, but the loop simply saved the data frames as "a", "b", "c"...I want to know if there is a way to attach those individual variables to a pre-existing name ("data_a.Rda", "data_b.Rda"...)

I am not particular about any method just as long as it works.

Suppose I have a directory like this:

/Documents (R home)
     |
     |-- my_data
             |
             |--data_1.Rda
             |--data_2.Rda

Then I can list the files in the my_data directory with:

list.files(path.expand("~/my_data/"))
#> [1] "data_1.Rda"  "data_2.Rda"

And I can generate the "next" Rda file path with a simple function:

next_rda <- function() {
  f <- list.files(path.expand("~/my_data/"), pattern = "^data_\\d+\\.Rda")
  num <- max(as.numeric(gsub("^data_(\\d)\\.Rda", "\\1", f)) + 1)
  paste0(path.expand("~/my_data/data_"), num, ".Rda")
}

So that I can do:

next_rda()
#> [1] "C:/Users/Administrator/Documents/my_data/data_3.Rda"

This means if I want to save an object I can do:

save(obj, file = next_rda())

Which will save to the next incremental file. Since the function checks the directory each time, it always writes to a new file, numbered appropriately.

I would check the existence of the filename. If it's exists, then create some sort mechanism to create a new filename. Whether it be a randomly generated string or a numbering system.

FYI: You could store multiple variables in 1 rda file by:

> save(data1, data2, data3, file = "data.rda")

Have a look at ?tempfile . It can generate unique filenames for you to use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM