Reputation: 10956
I built an R package and include a dataset called mouse
where I can access it using data(mouse)
. In the package, I also have a function called fun
which takes, as its first argument, the name of a dataset (included in the package):
fun = function(dt = NULL, ...) {
data(dt)
...
dt.sub = dt[ ,1:6]
...
}
However, when I use the function as fun(dt = "mouse")
, it says In data(dt) : data set ‘dt’ not found
. Also, I cannot use dt[ ,1:6]
since dt
here is a string. I tried to use noquote
and as.name
functions to get rid of the quotation marks, but the object dt
does NOT refer to the mouse dataset.
My question is, what's the best approach to pass the name of a dataset (mouse in this case) in the function argument, and then use it in the function body? Thanks!
Upvotes: 1
Views: 110
Reputation: 66842
Try this:
f <- function(dt = NULL) {
do.call("data", list(dt))
dt <- eval(as.name(dt))
head(dt)
}
Upvotes: 1