简体   繁体   中英

How can I save the results of a function in R without returning it?

I want to save the results of a function without returning it. I know that the variables in the function are local. I tried the followings, they return NULL .

function1 <- function(directory)
 {
  setwd(directory)
  #some codes
  save(list=ls(.GlobalEnv), file= "result.Rdata")
  # save.image(file= "result.Rdata")
 }

function1("~/Desktop")

Please tell more what do you want to achieve. Do you want to save the result in the file, or in the R workspace? In the first case

function1 <- function(directory) {
  setwd(directory)
  #some codes
  a <- 1
  save(list=ls(), file= "result.Rdata")
}

will do the trick. Note: you want to save current environment by ls() , not the global environment (unless you assign values there). But why do you want to save all variables from inside of a function, instead of just the important values?

If you want to save to the workspace, use assign() .

What about returning the results invisible

test <- function(x){
  return(invisible(x^2))
}
test(10) # no display of the result
abc <- test(10)
abc #contains 100

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