Encapsulating Dataset in R Package Function

27 Views Asked by At

When developing R package is it possible to encapsulate dataset within function and export that function. For example:

.f <- function(){
  
  utils::data("my_dataset", envir = environment())
  
  function(other_dataset){
    
    some_function(my_dataset, other_dataset)
  }
}

export_fun <- .f()

Is it possible to export function export_fun? I ask because it seems to me that this way dataset would be loaded only once and not every time the function is called.

1

There are 1 best solutions below

0
tpetzoldt On

One way is to use the /data folder in the package. Then the data are exported and need to be documented. For purely local data (e.g. specific method parameters), a simple approach is to define a local data set within an .R file in the package, e.g. foo.R and then use it in a function.

.mydata <- c(1.22, 4.33, 5.66)

foo <- function() {
  .mydata  * 2
}

Then export function foo, while .mydata remains internal.

This method is used in several CRAN packages.