Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 962
Joël Avatar asked Oct 23 '12 22:10

Joël


People also ask

How do you apply a function to all elements of a list in R?

lapply() function in R Programming Language is used to apply a function over a list of elements. lapply() function is used with a list and performs the following operations: lapply(List, length): Returns the length of objects present in the list, List.

How do I extract elements from a list in R?

The [[ operator can be used to extract single elements from a list. Here we extract the first element of the list. The [[ operator can also use named indices so that you don't have to remember the exact ordering of every element of the list. You can also use the $ operator to extract elements by name.

How do I extract elements from a vector in R?

To extract (also known as indexing or subscripting) one or more values (more generally known as elements) from a vector we use the square bracket [ ] notation.

Can you have a vector of lists in R?

Almost all data in R is stored in a vector, or even a vector of vectors. A list is a recursive vector: a vector that can contain another vector or list in each of its elements. Lists are one of the most flexible data structures in R.


1 Answers

Without mget():

do.call(mtable, lapply(models, as.symbol))
like image 55
Josh O'Brien Avatar answered Nov 15 '22 06:11

Josh O'Brien