[R] How to get a specific named element in a nested list

Keith Jewell k.jewell at campden.co.uk
Thu Nov 11 12:12:11 CET 2010


Neat!

I think replacing
     out <- rmatch(el, name)
with
    out <- Recall(el, name)
will avoid the dependence of the code on the function name

Keith J

"Michael Bedward" <michael.bedward at gmail.com> wrote in message 
news:AANLkTikV9ZEPxipbP7fTr8vMpGsJApTjyJ_DUdy-MRrR at mail.gmail.com...
On 11 November 2010 21:08, Janko Thyson <janko.thyson at ku-eichstaett.de> 
wrote:
>
> Could it be that you forgot to supply 'getEL()'? Or do I have to use some
> package to make it available?
>

Oops - no. The problem was me stupidly renaming the function without
modifying the code.  Try this instead...

rmatch <- function(x, name) {
 pos <- match(name, names(x))
 if (!is.na(pos))
   return(x[[pos]])

 for (el in x) {
   if (class(el) == "list") {
     out <- rmatch(el, name)
     if (!is.null(out)) return(out)
   }
 }
}


Sorry about that.

Michael


>> -----Ursprüngliche Nachricht-----
>> Von: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] 
>> Im
>> Auftrag von Michael Bedward
>> Gesendet: Donnerstag, 11. November 2010 10:56
>> An: friedericksen.hope at gmail.com
>> Cc: r-help at stat.math.ethz.ch
>> Betreff: Re: [R] How to get a specific named element in a nested list
>>
>> Hi Friedericksen,
>>
>> This function will do it. No doubt there are more elegant ways :)
>>
>> rmatch <- function(x, name) {
>> pos <- match(name, names(x))
>> if (!is.na(pos))
>> return(x[[pos]])
>>
>> for (el in x) {
>> if (class(el) == "list") {
>> out <- getEl(el, name)
>> if (!is.null(out)) return(out)
>> }
>> }
>> }
>>
>>
>> Michael
>>
>> On 11 November 2010 19:05, Friedericksen Hope
>> <friedericksen.hope at gmail.com> wrote:
>> > Hello,
>> >
>> > I have a nested named list structure, like the following:
>> >
>> > x <- list(
>> > list(
>> > list(df1,df2)
>> > list(df3,
>> > list(df4,df5))
>> > list(df6,df7)))
>> >
>> > with df1...d7 as data frames. Every data frame is named.
>> >
>> > Is there a way to get a specific named element in x?
>> >
>> > so, for example,
>> >
>> > x[[c("df5")]] gives me the data frame 5?
>> >
>> > Thank you in advance!
>> >
>> > Best,
>> > Friedericksen
>> >
>> > ______________________________________________
>> > R-help at r-project.org mailing list
>> > https://stat.ethz.ch/mailman/listinfo/r-help
>> > PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
>> > and provide commented, minimal, self-contained, reproducible code.
>> >
>>
>> ______________________________________________
>> R-help at r-project.org mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
>
>



More information about the R-help mailing list