0

Question: Is it possible to read R objects from an RData file only if they don't exist in the current environment?

Why: I'd like to be able to set some variables at the top of an R script, but load in a previous script's finished variables. If they are set at the top, though, I'd like them to override the load() variables.

Example data and problem:

a <- 5
b <- 2
save(a,b,file="testa.RData")
rm(a)
a <- 10
load("testa.RData")
#CURRENTLY:
> a
[1] 5
> b
[1] 2

#DESIRED RESULT:
> a
[1] 10
> b
[1] 2
Roland
  • 127,288
  • 10
  • 191
  • 288
Neal Barsch
  • 2,810
  • 2
  • 13
  • 39
  • Possible duplicate of [Get specific object from Rdata file](https://stackoverflow.com/questions/8700619/get-specific-object-from-rdata-file) – krads Oct 17 '18 at 06:44
  • 1
    I suggest you use `saveRDS` to save each variable to its own file. Then you can load the files depending on whether `exists` returns `TRUE`. – Roland Oct 17 '18 at 06:52
  • I went with loading the file into a new environment and calling by name via the Get specific object from Rdata file from @krads suggestion. `e <- local({load("testa.RData"); environment()});if(!exists("a"))a<-e$a` – Neal Barsch Oct 17 '18 at 07:02

1 Answers1

1

I figured out a fairly clean function to do it based on the comments suggestions:

 lnexist <- function(filename){
  ee <- local({load(filename); environment()})
  lsee <- ls(ee)
  lse <- ls()
  for(x in lsee){
    if(!exists(x)){
      tempvar <<- ee[[x]]
      assign(x,tempvar,envir = .GlobalEnv)
    }
  }
}

#TESTING
a<- 10
b <- 5
c <- 3
save(a,b,c,file="testc.RData")
rm(b)
c<- 8
lnexist("testc.RData")
> a
[1] 10
> b
[1] 5
> c
[1] 8
Neal Barsch
  • 2,810
  • 2
  • 13
  • 39