Reputation: 2452
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
Upvotes: 2
Views: 176
Reputation: 886938
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
Upvotes: 3