R: relisting a flat list -


this question has nice solution of flattening lists while preserving data types (which unlist not):

flatten = function(x, unlist.vectors=f) {     while(any(vapply(x, is.list, logical(1)))) {         if (! unlist.vectors)             x = lapply(x, function(x) if(is.list(x)) x else list(x))         x = unlist(x, recursive=f)     }     x } 

if give following list, behaves expected:

> = list(c(1,2,3), list(52, 561), "a") > flatten(a) [[1]] [1] 1 2 3  [[2]] [1] 52  [[3]] [1] 561  [[4]] [1] "a" 

now i'd restructure flat list a. relist fails miserably:

> relist(flatten(a), skeleton=a) [[1]] [[1]][[1]] [1] 1 2 3  [[1]][[2]] [1] 52  [[1]][[3]] [1] 561  [[2]] [[2]][[1]] [[2]][[1]][[1]] [1] "a"  [[2]][[2]] [[2]][[2]][[1]] null  [[3]] [[3]][[1]] null 

now, of course relist(unlist(b), a) loses data types again. way restructure flat list?

bonus points if handles analogous attribute unlist.vectors correctly.

one way is:

relist2 = function(x, like, relist.vectors=f) {     if (! relist.vectors)          = rapply(a, function(f) na, how='replace')     lapply(relist(x, skeleton=like), function(e) unlist(e, recursive=f)) } 

this retains classes , distinguishes between lists , vectors:

> relist2(flatten(a), like=a) [[1]] [1] 1 2 3  [[2]] [[2]][[1]] [1] 52  [[2]][[2]] [1] 561  [[3]] [1] "a"  > relist2(flatten(a, unlist.vectors=t), like=a, relist.vectors=t) [[1]] [1] 1 2 3  [[2]] [[2]][[1]] [1] 52  [[2]][[2]] [1] 561  [[3]] [1] "a" 

Comments

Popular posts from this blog

windows - Single EXE to Install Python Standalone Executable for Easy Distribution -

c# - Access objects in UserControl from MainWindow in WPF -

javascript - How to name a jQuery function to make a browser's back button work? -