Data not found in package

I've come across an issue when creating my package related to data stored within the package itself. When running code after loading with library(), data can be accessed as normal, but if I run the code using :: in command line, it does not work.

For example, the following script generates a small toy package (requires usethis & devtools):

# Create package and move into it
usethis::create_package("toy")
setwd("toy")

# Edit Description to be plain
writeLines("Package:toy\nVersion:0.1\nLazyData: true","DESCRIPTION")

# Create a function to access it
writeLines("#' show_data\n#' @export\nshow_data <- function() toy_data","R/show_data.R")

# Document this function
devtools::document()

# Create the toy dataset
set.seed(100)
toy_data <- data.frame(x = rnorm(10),y=rnorm(10))
usethis::use_data(toy_data)

# Install the package
devtools::install()

# Move back out of the package folder
setwd("..")

If I run this within R, it runs fine whether I use library(toy) or toy::show_data().
If I run on command line with R -e "library(toy);show_data()", it runs fine as the data is loaded when the package is loaded.
However, when I run R -e "toy::show_data()", I get an error:

> toy::show_data()
Error in toy::show_data() : object 'toy_data' not found
Execution halted

What is the best way to make this data accessible when using :: in command line?

Hi Michael - thanks for linking to this on Twitter :grinning:

This works for me if you add toy::toy_data in the show_data() function definition. Here's a slightly slimmer version of your code:

usethis::create_package("toy")
setwd("toy")

writeLines("#' show_data\n#' @export\nshow_data <- function() toy::toy_data","R/show_data.R")

# Create the toy dataset
set.seed(100)
toy_data <- data.frame(x = rnorm(10),y=rnorm(10))
usethis::use_data(toy_data)
devtools::document()
# Install the package
devtools::install()

toy::show_data()

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.