user3032689
user3032689

Reputation: 667

Save-function in R

I would like to use a custom function to save my R functions to a file. I made the following:

savefun <- function(){
  rm(list = setdiff(ls(), lsf.str())) # to remove all variables first
  save.image(paste0("fun",".RData"))
}

Now the 2 lines do work in global, but not within the function.

Test by making some random variables:

x <- 1243
y <- 39934934

Those are not deleted by rm(list = setdiff(ls(), lsf.str())). I tried to fix it by changing the environment, but it doesn't work.

Any hints?

Upvotes: 1

Views: 1018

Answers (2)

Ben Bolker
Ben Bolker

Reputation: 226971

I still don't see why

savefun <- function(file="fun.RData") {
  save(list=lsf.str(envir = .GlobalEnv), file=file)
}

wouldn't be more straightforward ... (thanks to @sebastian-c for the envir= reminder)

Upvotes: 2

sebastian-c
sebastian-c

Reputation: 15425

You need to make sure that all of your searches (ls, lsf.str, rm) look in the global environment:

x <- 1243
y <- 39934934

savefun <- function(){
  rm(list = setdiff(ls(envir = .GlobalEnv), lsf.str(envir = .GlobalEnv)), envir = .GlobalEnv) # to remove all variables first
  save.image(paste0("fun",".RData"))
}

savefun()

Upvotes: 2

Related Questions