Joël
Joël

Reputation: 83

How can I use list/vector elements as objects arguments to a function in R?

I programmatically evaluated several models, whose names are in a vector models. How can I then use the function mtable with them, calling them programmatically?

Here is an example :

library(memisc)
a <- rnorm(100,0,1)
b <- rnorm(100,0,1)
c <- rnorm(100,0,1)
d <- rnorm(100,0,1)
mod1 <- lm(a ~ b)
mod2 <- lm(c ~ d)
models <- c("mod1", "mod2")
mtable(mget(models,envir=globalenv()))

I then get an error: "no method available for 'getSummary' for an object of class 'list'".

What can I do? I tried call and do.call but without success.

Upvotes: 5

Views: 1375

Answers (3)

Mars
Mars

Reputation: 8854

The other answers were helpful to me, as well, but the focus Joel's particular example obscured the general point, which I figured out by experimenting. It's this:

Given a function which accepts a variable number of arguments:

fvar <- function(...) {do something}

suppose that the arguments you want to pass are already contained in a list:

myargs <- list(a=1:3, b=c(2, 3, 4))

You could pass them individually, e.g.:

fvar(myargs[[1]], myargs[[2]])

but that only works if your code knows the structure of the list.

do.call() allows you to pass whatever is in your list as the series of arguments given to the function:

do.call(fvar, myargs)

This is more general, since your code doesn't have to figure out what the list's particular structure is, as long as you can assume that it's appropriate for the function.

(do.call does essentially the same thing as Common Lisp's apply, by the way.)

Upvotes: 1

Josh O&#39;Brien
Josh O&#39;Brien

Reputation: 162341

Without mget():

do.call(mtable, lapply(models, as.symbol))

Upvotes: 5

flodel
flodel

Reputation: 89057

Using do.call:

do.call(mtable, mget(models,envir=globalenv()))

Upvotes: 3

Related Questions