Reputation: 1091
How can I write a function that takes an argument which is passed to the data
function in R.
As a simple example
load_data <- function(mydata) {
x <- data(mydata)
x
}
If I tried to use this to load iris
load_data(mydata = "iris")
The function just returns "data set mydata not found"
My end goal here is to have a function that attaches a dataset to the function's environment, and then the function would do some arbitrary calculations.
Upvotes: 1
Views: 83
Reputation: 1335
If you want iris
to be stored in x
then you don't need to call data
at all.
load_data <- function(mydata) {
x <- mydata
x
}
load_data(iris)
Upvotes: 1
Reputation: 206197
If you want data()
to evaualte that character string, it needs to be passed via list=
load_data <- function(mydata) {
x <- data(list=mydata)
x
}
I'm not sure what you were expecting to be returned but the ?data
help page tells you it just returns the name of the data sets loaded, not the data itself.
If you only want it to load into the function scope, then also set the environment=
parameter
load_data <- function(mydata) {
data(list=mydata, environment=environment())
}
Upvotes: 4