Search code examples
rfunctionr-package

How to save data dynamically for R package?


I want to save dynamic data or dataframe (because it depends on parameters) inside a function and want to use this saved data another function. I thought of using saveRDS(), but since I work in my local, I didn't know if it would work when I made it public. I don't get any errors, warnings or notes when I check, but I'm looking for a better solution.

get_data <- function(startDate,endDate){
  
  df <- ... # dynamic
  
  saveRDS(df,"df.rds")
  
}

funcx <- function(){
  
  df2 <- readRDS("df.rds")
  
}

Thanks in advance.


Solution

  • 1) As mentioned in the comments just pass the data using the return value of the first function and arguments of the second.

    get_data <- function(startDate, endDate) {
      data.frame(startDate, endDate)
    }
    
    funcx <- function(df){
      print(df)
    }
    
    get_data(1, 2) |> funcx()
    

    or store the data in your workspace and then get it from there:

    Data <- get_data(1, 2)
    funcx(Data)
    

    or put it in an option

    options(Data = get_data(1, 2))
    funcx(getOption("Data"))
    

    2) Use a local environment:

    e <- local({
      df <- NULL
      get_data <- function(startDate, endDate) {
        df <<- data.frame(startDate, endDate)
      }
      funcx <- function(){
        print(df)
      }
      environment()
    })
    
    e$get_data(1, 2)
    e$funcx()
    

    or put the environment right in the package. Look at lattice.options and lattice.getOption source code in the lattice package for an example of this where it uses the .LatticeEnv environment that is stored right in the package itself.

    library(lattice)
    ls(lattice:::.LatticeEnv)
    lattice.options # displays source code of lattice.options
    lattice.getOption # displays source code
    

    3) The proto package can be used to clean up (2) a bit. proto objects are environments having their own methods. See the package vignette and help files.

    library(proto)
    
    p <- proto(
          get_data = function(., startDate, endDate) {
            .$df <- data.frame(startDate, endDate)
          },
          funcx = function(.) {
            print(.$df)
          }
    )
    p$get_data(1, 2)
    p$funcx()