2

Consider a nested list with data that is basically rectangular.

mylst1 <- list(
  "system" = list(
    "subjectId" = c(101,102,103),
    "procedureId" = c(202,202,203)
  ),
  "demographics" = list(
    "demo_age" = c(12,22,32),
    "demo_gender" = c(1,0,1)
  ),
  "items" = list(
    "N" = list(
      "n001" = c(1,2,3),
      "n002" = c(3,2,1)
      ),
    "E" = list(
      "e001" = c(1,2,3),
      "e002" = c(3,2,1)
    )
  )
)

Since nested lists are awkward to work with, let's create a data frame: myDf <- data.frame(mylst1)

So far so good, now I can perform all my operations on myDf. Let's assume i just filtered some observations. The problem is that I need to return the same nested list structure as required by the web application I want to send this data to, but now the data of course looks like this:

> str(myDf)    
'data.frame':   3 obs. of  8 variables:
     $ system.subjectId        : num  101 102 103
     $ system.procedureId      : num  202 202 203
     $ demographics.demo_age   : num  12 22 32
     $ demographics.demo_gender: num  1 0 1
     $ items.N.n001            : num  1 2 3
     $ items.N.n002            : num  3 2 1
     $ items.E.e001            : num  1 2 3
     $ items.E.e002            : num  3 2 1

What would be the best solution to get this data in the original list format? I was thinking of using the . as a delimiter for each level, but i'm unsure how to do this in practice.

Thanks

1 Answer 1

3

One option would be relist (assuming that the columns are all of the same class) as in the 'myDf'

newlst <- relist(unlist(myDf), skeleton = mylst1)
identical(mylst1, newlst)
#[1] TRUE
Sign up to request clarification or add additional context in comments.

3 Comments

One major caveat (I believe) is that the number of elements in myDF cannot change (no added or removed rows). A second potential issue is that unlist will coerce all elements to the same type.
@lmo Yeah that is right, and i added the assumption about the same class
Thank you! I didn't know about relist()! As lmo pointed out, the problem is that i now cannot add or remove cases. Is there a work around here?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.