[R] Print list structure

Duncan Murdoch murdoch at stats.uwo.ca
Mon Nov 5 19:17:44 CET 2007


On 11/5/2007 12:01 PM, Martin Morgan wrote:
> Hi Antje,
> 
> I know you have a solution, but
> 
>> l <- list(list(L=1,list(L=2)))
>> f <- function() { i=1; function(...) {cat("level", i, ":", ...); i<<-i+1 }}
>> r=rapply(l, f(), "..."="\n")
> level 1 : 1 
> level 2 : 2 
> 
> lets you use R scoping rules and a relatively new addition to the
> 'apply' family of functions. It also points to a bit of awkwardness in
> the signature for rapply (maybe it would have been more consistent
> with rapply(X, FUN, ..., classes="ANY", etc)

That doesn't work in the sense that "level" doesn't report on the 
recursion level.  For example,

 > l <- list(list(L=1,list(L=2), M=3))
 > str(l)
List of 1
  $ :List of 3
   ..$ L: num 1
   ..$  :List of 1
   .. ..$ L: num 2
   ..$ M: num 3

 > f <- function() { i=1; function(...) {cat("level", i, ":", ...); 
i<<-i+1 }}
 > r=rapply(l, f(), "..."="\n")
level 1 : 1
level 2 : 2
level 3 : 3

The i variable ends up being a simple counter, it doesn't get reset when 
you go back up a level.  I don't know how to make rapply do what we want 
here.

Duncan Murdoch


> 
> Martin
> 
> Duncan Murdoch <murdoch at stats.uwo.ca> writes:
> 
>> On 11/5/2007 8:34 AM, Antje wrote:
>>> Hello again,
>>> 
>>> I was wondering whether there is a command with which I can print the structure 
>>> of a list, containing list of list of ...
>>> If you have any hint let me know...
>>
>> str() can print the structure of any R object.
>>
>> Duncan Murdoch
>>
>> ______________________________________________
>> R-help at r-project.org mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list