So I need to use data in my R package functions. All is well if I do library(myPkg) and then use the function I need e.g.:
library(myPkg)
c_my_data(2)
[1] "A" "2"
But I can’t use the function if I don’t attach the package.
Restarting R session…
myPkg::c_my_data(2)
Error in myPkg::c_my_data(2) : object 'my_data' not found
I use roxygen2 to generate the NAMESPACE file and it says:
Datasets: all datasets are publicly available. They exist outside of the package namespace and must not be exported.
The NAMESPACE file:
# Generated by roxygen2: do not edit by hand
export(c_my_data)
The c_my_data.R file:
#' Data Adder
#' @param x a number
#' @export
c_my_data<- function(x) {
c(my_data, x)
}
The data.R file:
#' My data
#' A vector
#' @format ## `my_data`
#' A vector
#' \describe{
#' \item{A}{Letter}
#' }
#' @source Me
"my_data"
Is there any way I can add the data so that myPkg::c_my_data(2) would work?
>Solution :
You could try using MyPkg::my_data in your function definition, if you expect that function to work without MyPkg loaded. You just used my_data and assumed R would know where to find it.
This works when MyPkg is loaded, but stops working if it is not. So be verbose about where to find the dataset!
And a sidenote:
I think you should call the R script containing data documentation exactly like your data, e.g. my_data.R. Data sets are not exported to the namespace, so this may be important.
Refer to the R packages online book by Wickham, see the data chapter.