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!

>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"))

Leave a Reply