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

Michael Bedward michael.bedward at gmail.com
Thu Nov 11 10:55:41 CET 2010


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.
>



More information about the R-help mailing list