Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing same named list elements of the list of lists in R

Tags:

r

Frequently I encounter situations where I need to create a lot of similar models for different variables. Usually I dump them into the list. Here is the example of dummy code:

modlist <- lapply(1:10,function(l) {
   data <- data.frame(Y=rnorm(10),X=rnorm(10))
   lm(Y~.,data=data)
})

Now getting the fit for example is very easy:

lapply(modlist,predict)

What I want to do sometimes is to extract one element from the list. The obvious way is

sapply(modlist,function(l)l$rank)

This does what I want, but I wonder if there is a shorter way to get the same result?

like image 315
mpiktas Avatar asked May 09 '11 10:05

mpiktas


People also ask

How do I view a specific element in a list in R?

Accessing List Elements. Elements of the list can be accessed by the index of the element in the list. In case of named lists it can also be accessed using the names.

Can a list contain a list in R?

The list data structure in R allows the user to store homogeneous (of the same type) or heterogeneous (of different types) R objects. Therefore, a list can contain objects of any type including lists themselves.

How do I retrieve an element 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.

What does list () do in R?

The list() function in R is used to create a list of elements of different types. A list can contain numeric, string, or vector elements.


2 Answers

probably these are a little bit simple:

> z <- list(list(a=1, b=2), list(a=3, b=4))
> sapply(z, `[[`, "b")
[1] 2 4
> sapply(z, get, x="b")
[1] 2 4

and you can define a function like:

> `%c%` <- function(x, n)sapply(x, `[[`, n)
> z %c% "b"
[1] 2 4

and also this looks like an extension of $:

> `%$%` <- function(x, n) sapply(x, `[[`, as.character(as.list(match.call())$n))
> z%$%b
[1] 2 4
like image 90
kohske Avatar answered Oct 21 '22 19:10

kohske


I usually use kohske way, but here is another trick:

 sapply(modlist, with, rank)

It is more useful when you need more elements, e.g.:

 sapply(modlist, with, c(rank, df.residual))

As I remember I stole it from hadley (from plyr documentation I think).

Main difference between [[ and with solutions is in case missing elements. [[ returns NULL when element is missing. with throw an error unless there exist an object in global workspace having same name as searched element. So e.g.:

dah <- 1
lapply(modlist, with, dah)

returns list of ones when modlist don't have any dah element.

like image 29
Marek Avatar answered Oct 21 '22 19:10

Marek