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

3

5

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.

Garganey answered 23/10, 2012 at 22:18 Comment(0)
C
3

Using do.call:

do.call(mtable, mget(models,envir=globalenv()))
Cush answered 23/10, 2012 at 22:23 Comment(1)
Thanks, this works! I tried different combinations with do.call but apparently not this very simple one... ashamedElah
K
5

Without mget():

do.call(mtable, lapply(models, as.symbol))
Kaslik answered 23/10, 2012 at 22:26 Comment(0)
C
3

Using do.call:

do.call(mtable, mget(models,envir=globalenv()))
Cush answered 23/10, 2012 at 22:23 Comment(1)
Thanks, this works! I tried different combinations with do.call but apparently not this very simple one... ashamedElah
F
1

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.)

Fourthclass answered 5/1, 2013 at 19:4 Comment(3)
I think you want fvar(myargs[[1]], myargs[[2]]), or even fvar(a=myvar[[1]], b=myvar[[2]]).Rosser
(Realized that the comment I was trying to add wasn't relevant, but can't delete it completely.)Fourthclass
Maybe there would be situations in which myargs[1] would be appropriate, but you're right. I'll edit the answer.Fourthclass

© 2022 - 2024 — McMap. All rights reserved.