Load a dataset into R with data() using a variable instead of the dataset name
Use the variable as character. Otherwise you will be processing the contents of "Titanic" rather than its name. You may also need to use get in order to convert the character value to an object name.
myvar <- 'Titanic'
myfun <- function(mydataset) {
data(list=mydataset)
str(get(mydataset))
}
myfun(myvar)
If the package has been loaded, you can use the get() function to assign the data set to a local variable:
data_object = get(myvar, asNamespace('<package_name>'))
or simply:
data_object = get(myvar)
Use the list
argument. See ?data
.
data(list=myvar)
You'll also need myvar
to be a character string.
myvar <- "Titanic"
Note that myvar <- Titanic
only worked (I think) because of the lazy loading of the Titanic data set. Most datasets in packages are loaded this way, but for other kinds of data sets, you'd still need the data
command.