Home > front end >  Restructuring an arbitrarily nested list
Restructuring an arbitrarily nested list

Time:11-06

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!

CodePudding user response:

Using a recursive function with rrapply

library(rrapply)
out <- rrapply(l, condition = function(x, .xname)
         .xname %in% c('id', 'field'), how = "flatten" )

out2 <- unname(split(as.list(out), cumsum(names(out) == "id")) )

-checking with expected output

> identical(goal, out2)
[1] TRUE

CodePudding user response:

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