tags:

views:

77

answers:

1

I want to create a function that takes a dataset name and a package name and returns the dataset as data.frame. Here is my try

loadDataSet <- function(name, pkg) {
      varname <- data(name, package=pkg)
      return(get(varname[[1]]))
    }
loadDataSet("acme", "boot")

However, this function fails. The problem seems to be, that the call to data() does not look up the value of the name variable, but rather "name".

I already know how to go from a variable to its name, via deparse(substitute(var)). But how do I go the other way, from "var" to var?

Any hint appreciated!

+4  A: 

Give this a try

loadDataSet <- function(name, pkg) {
      do.call("data", list(name,package=pkg))
      return(get(name))
    }

loadDataSet("acme", "boot")
gd047
If you don't want the data set printed to the console, use `invisible` instead of `return`.
Joshua Ulrich
Well, that sure helped. Thanks! I have now a similar problem with table(). Say I attached cgd from survival and want now table(sex, treat), but have again only strings "sex" and "treat". How can I do that? do.call("table", list("sex", "treat")) failed...
Karsten W.
try this: return(do.call("table", list(eval(parse(text=var1)), eval(parse(text=var2)))))
gd047
thanks again, works perfectly!
Karsten W.