Is there any way I can add/update an object in the internal R package data (`R/sysdata.rda`), albeit inadvisable?

301 Views Asked by At

I have an R package with internal data (by design stored in R/sysdata.rda). I would like to update one of the objects in it, or add an object to it.

The usethis package has the use_data() and use_data_raw(), but they do not (and seem to will not) support this possibility (see r-lib/usethis#1512 and r-lib/usethis#1091).

How can this still be accomplished? I would like to not interfere with my global (user) environment.

1

There are 1 best solutions below

4
MS Berends On BEST ANSWER

This answer is just a solution for a specified use case. Whether this is a recommendable workflow is not part of this question or answer. I only show how this can be made possible in R.

Problem explanation

Per the usethis::use_data() documentation, it is indeed not possible to do this, as the ... must contain "Unquoted names of existing objects to save" (so you cannot add a list with objects) and there is no add argument:

use_data(
  ...,
  internal = FALSE,
  overwrite = FALSE,
  compress = "bzip2",
  version = 2,
  ascii = FALSE
)

use_data_raw(name = "DATASET", open = rlang::is_interactive())
Solution

You can load your current sysdata.rda to a separate environment, alter it (by adding of changing objects) and then save it again using save() (that use_date() actually calls internally):

# create new environment
my_new_env <- new.env()

# load current internal data into this new environment
load("R/sysdata.rda", envir = my_new_env)

# add or replace some objects
my_new_env$dataset123 <- data.frame(a = 1, b = 2)

# save the environment as internal package data
save(list = names(my_new_env),
     file = "R/sysdata.rda",
     envir = my_new_env)

Though for the best portability and lowest space used, you might want to use:

save(list = names(my_new_env),
     file = "R/sysdata.rda",
     ascii = FALSE,
     version = 2,
     compress = "xz",
     envir = my_new_env)