Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Restructuring an arbitrarily nested list

I have a list with the following structure:

  l <- list(condition = "AND", 
            rules = list(list(id = "sex", 
                              field = "sex"),
                         list(condition = "AND", 
                              rules = list(
                                list(id = "species",
                                     field = "species"), 
                                list(condition = "AND",
                                     rules = list(
                                       list(id = "bill_length_mm", 
                                            field = "bill_length_mm")))))), 
            valid = TRUE)

and I would like to convert to this structure

  goal <- list(
    list(id = "sex",
         field = "sex"),
    list(id = "species",
         field = "species"),
    list(id = "bill_length_mm", 
         field = "bill_length_mm")
    )

The solution would need to be flexible enough to handle more/less rules elements. Any suggestions on how I can do this would be greatly appreciated!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It looks like you could use a recursive strategy here. This will look for lists that have an id elemenet and will return them as a list.

get_fields <- function (x) {
  if (is.list(x)) {
    if (!is.null(x$id)) {
      return(list(x))
    } else {
      unname(do.call("c", lapply(x, get_fields)))
    }
  } else {
    NULL
  }
}
dput(result<-get_fields(l))
# list(list(id = "sex", field = "sex"), list(id = "species", field = "species"), 
#    list(id = "bill_length_mm", field = "bill_length_mm"))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading