Reputation: 7061
I have included a few internal data sets during building a local R package such as data_abc, data_cdj, ..., data_mnp
. Then I am attempting to write a function to call one of these datasets depending on the user's input argument p
which will abc
, cdj
, ...
, mnp
such as:
get_data <- function(p) {
use_data <- paste0('data_', 'p')
...
return(use_data)
}
Since use_data <- paste0('data_', 'p')
is a string, my question is how to make the function return the internal data such as data_mnp
if p = 'mnp'
.
Upvotes: 0
Views: 290
Reputation: 5429
I think this is how you need to do it, but I'd love to be corrected.
get_data <- function(p) {
data_name = paste0( "data_", p )
# check first that it exists in your package:
ns <- getNamespace("your.package.name")
if(!exists(data_name, where=ns, inherits=FALSE)) {
stop( "a data set with suffix ", p, " does not exist!")
}
return( get( data_name, where=ns, inherits=FALSE ) )
}
Upvotes: 1