Search code examples
rpackagedataset

How can I automatically load all data sets from my own package


Assume I have two packages

  • package1
    • data sets d1, d2, d3
  • package2 which should use data sets from package1

package1 contains data sets, which I want to use for testing. I can access each of these via e.g. package1::d1. But how can I load all of them in an automated way?

Something like

ds <- data(package = "package1") # you can try e.g. "carData"
ds$results[1, 3] # gives the first entry
mydataset <- load(ds$results[1, 3]) # this does not work

Other will use both packages, so it should work for others and on different platforms (Windows, Mac) Any ideas?


ds$results[1, 3]
#  Item 
#  "d1" 

looks promising, but

data(ds$results[1, 3])
# Warning message:
# In data(ds$results[1, 3]) : data set ‘ds$results[1, 3]’ not found

Solution

  • I just realized, there are two options:

    You want to load external files from inst/extdata

    pathExtData <- system.file("extdata", package = "myPackage")
    allFilenames <- list.files(pathExtData, full.names = TRUE)
    # e.g. in case of Excel files
    datalist <- list()
    for (i in 1:length(allFilenames)) {
      datalist[[i]] <- readxl::read_xlsx(path = allFilenames[i], sheet = "mySheet")
    }
    

    You want to load RData from a package you can use

    ds <- data(package = "myPackage")
    datalist <- list()
    for (i in 1:length(ds$results[, 3])) {
      eval(parse(text = paste0("datalist[[", i, "]] <- myPackage::", ds$results[i, 3])))
    }