[R] fast subsetting of lists in lists

Gabor Grothendieck ggrothendieck at gmail.com
Tue Dec 7 15:54:50 CET 2010


On Tue, Dec 7, 2010 at 9:47 AM, Alexander Senger
<senger at physik.hu-berlin.de> wrote:
> Hello,
>
>
> my data is contained in nested lists (which seems not necessarily to be
> the best approach). What I need is a fast way to get subsets from the data.
>
> An example:
>
> test <- list(list(a = 1, b = 2, c = 3), list(a = 4, b = 5, c = 6),
> list(a = 7, b = 8, c = 9))
>
> Now I would like to have all values in the named variables "a", that is
> the vector c(1, 4, 7). The best I could come up with is:
>
> val <- sapply(1:3, function (i) {test[[i]]$a})
>
> which is unfortunately not very fast. According to R-inferno this is due
> to the fact that apply and its derivates do looping in R rather than
> rely on C-subroutines as the common [-operator.
>
> Does someone now a trick to do the same as above with the faster
> built-in subsetting? Something like:
>
> test[<somesubsettingmagic>]
>
>

This does not involve apply.  You could time it to see if its any faster:

> test.un <- unlist(test)
> unname(test.un[names(test.un) == "a"])
[1] 1 4 7

-- 
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com



More information about the R-help mailing list