0

here is an issue I have been struggling with. I am trying to automate some rather long estimations. The for loop I built for the estimations themselves works fine, but I would like to write each of the estimation results onto my drive. I really need to do this estimation by estimation as the resulting files are very large, and I cannot hold more than 3-4 in memory.

Here is an example of what I would like to do:

for (i in 1:n){
d <- da %>% filter(index == i)
h <- estimate(f(d)) #not real code; this create my output stored in h
saveRDS( h , file = "model_[i].Rda")
}

Again, this all works fine except for saving the file in the last line. Any ideas of what I could do here?

Cheers, Max

  • 1
    Can you clarify: in what way does the file save not work? Is there an error message? Does it save a blank file? ...? – Jason Jun 19 '21 at 06:44
  • It saves the file as "model_[i].Rda", and keeps overwriting this file. What I would need is a series of files of the following form: "model_1.Rda" , "model_2.Rda", etc. – Max Montana Jun 19 '21 at 06:46
  • 1
    You can't just include variables in strings in R and have them be evaluated. Use `paste()` to build your file name. Or there is the `glue` package which does do interpolation. Something like `saveRDS( h , file = glue::glue("model_{i}.Rda"))` – MrFlick Jun 19 '21 at 06:56
  • `stringr::str_c('model_', i, '.Rda')` can also work. – jpdugo17 Jun 19 '21 at 06:59
  • Thanks MrFlick, that works! Evidently some bad habits I picked up using Stata that I need to get rid of ... much appreciated! – Max Montana Jun 19 '21 at 07:29

0 Answers0