0

I made multiple models and stored them in separate names in a loop

df <- data.frame(loc.id = rep(1000:1009,each = 20), y = rnorm(20*10), x = rnorm(20*10))

loc.vec <- c(1000:1009)

for(l in seq_along(loc.vec)){

      loc <- loc.vec[[l]]
      df.loc <- df[df$loc.id == loc,]
      mdl <- with(df.loc,lm(y ~ x))
      saveRDS(mdl,paste0("mod",loc,".mg.",".rda"))
      rm(mdl)
  }

When I try to reload the model in the loop:

  loc.vec <- c(1000:1009)

  for(l in seq_along(loc.vec)){

    loc <- loc.vec[[l]]
    readRDS(paste0("mod",loc,".mg.",".rda"))
  }

How do I load them such that my global environment has models as mod.1000.mg, mod.1001.mg, mod.1002.mg and so on

89_Simple
  • 3,393
  • 3
  • 39
  • 94
  • Actually it was just for demonstration purpose. The models are saved by different names as demonstrated – 89_Simple Jun 07 '18 at 12:39
  • Could you show a reproducible example for testing – akrun Jun 07 '18 at 12:40
  • 3
    1. It's a bad idea to create numerous variables with generated names. Just put the results in a list. 2. If you're using `saveRDS`, you should use `readRDS` to read the file, not `load`. – user2554330 Jun 07 '18 at 12:43
  • Thank you . I have edited my question and also tried your suggestions. However, my global environment is empty – 89_Simple Jun 07 '18 at 12:50
  • I suggest looking at the `lmList` function in the `lme4` package. – James Jun 07 '18 at 12:51
  • YOu may need to assign it – akrun Jun 07 '18 at 12:51
  • [Lists](https://stackoverflow.com/questions/2050790/how-to-correctly-use-lists-in-r?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa) [are](http://www.r-tutor.com/r-introduction/list) [great](https://www.r-bloggers.com/how-to-use-lists-in-r/)[!](http://r4ds.had.co.nz/lists.html) – LAP Jun 07 '18 at 12:52

0 Answers0