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

Michael Bedward michael.bedward at gmail.com
Thu Nov 11 11:45:43 CET 2010


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