2

As a follow-up question to Flatten list and push list key to vector on second level , I'm now looking for an efficient way to reverse the procedure earlier described. In summary, I need to restructure a flat list from this:

> str(myList)
List of 9
 $ ID               : num [1:2] 13454 13455
 $ subjectId        : num [1:2] 187 188
 $ procedureId      : num [1:2] 3 3
 $ procedureSampleId: num [1:2] 3 3
 $ timestamp        : chr [1:2] "2017-04-21T17:15:10.911Z" "2017-04-21T17:15:10.913Z"
 $ n001             : num [1:2] -999 -999
 $ n002             : num [1:2] -999 -999
 $ gender           : num [1:2] 1 -999
 $ age              : num [1:2] 18 28 

to this:

$ 13454:List of 8
  ..$ subjectId        : num 187
  ..$ procedureId      : num 3
  ..$ procedureSampleId: num 3
  ..$ timestamp        : chr "2017-04-21T17:15:10.911Z"
  ..$ n001             : num -999
  ..$ n002             : num -999
  ..$ gender           : num 1
  ..$ age              : num 18

 $ 13455:List of 8
  ..$ subjectId        : num 188
  ..$ procedureId      : num 3
  ..$ procedureSampleId: num 3
  ..$ timestamp        : chr "2017-04-21T17:15:10.913Z"
  ..$ n001             : num -999
  ..$ n002             : num -999      
  ..$ gender           : num -999
  ..$ age              : num 28

Whereas each ID column should be a list of its own. So far I've been using for-loops to accomplish this, but it turned out to be highly inefficient.

Reproducible code:

myList <- list('ID' = c(13454,13455), 'subjectId' = c(187,188), 'procedureId' = c(3,3), 'procedureSampleId' = c(3,3), 'timestamp' = c("2017-04-21T17:15:10.911Z", "2017-04-21T17:15:10.913Z"), 'n001' = c(-999,-999), 'n002' = c(-999,-999), 'gender' = c(1,-999), 'age' = c(18,28))
Community
  • 1
  • 1
Comfort Eagle
  • 2,112
  • 2
  • 22
  • 44

2 Answers2

2

One option would be transpose from purrr

library(tidyverse)
res <- myList %>%
             transpose %>%
             map(~.[-1])
names(res) <- myList[[1]]
akrun
  • 874,273
  • 37
  • 540
  • 662
1

A base R alternative would be to use a nested lapply and setNames to add the ID as outer level list names.

myNestList <- setNames(lapply(1:2,
                       function(i) lapply(myList[-1], "[", i)), myList[[1]])

which results in

str(myList)
List of 2
 $ :List of 8
  ..$ subjectId        : num 187
  ..$ procedureId      : num 3
  ..$ procedureSampleId: num 3
  ..$ timestamp        : chr "2017-04-21T17:15:10.911Z"
  ..$ n001             : num -999
  ..$ n002             : num -999
  ..$ gender           : num 1
  ..$ age              : num 18
 $ :List of 8
  ..$ subjectId        : num 188
  ..$ procedureId      : num 3
  ..$ procedureSampleId: num 3
  ..$ timestamp        : chr "2017-04-21T17:15:10.913Z"
  ..$ n001             : num -999
  ..$ n002             : num -999
  ..$ gender           : num -999
  ..$ age              : num 28
lmo
  • 37,904
  • 9
  • 56
  • 69