Skip to content

how to flatten a list to the same level?

3 messages · Mark Heckmann, Henrique Dallazuanna

#
I have a nested list l like:

l <- list(A=c(1,2,3), B=c("a", "b"))
l <- list(l,l, list(l,l))

I want the list to be unlisted, but not on the lowest level of each  
"branch".
I want the lowest level of each list branch to remain as it is.
So unlist or unlist(rec=F) do not work here as the level of nesting  
may differ on the elements.
The result should look like:

$A
[1] 1 2 3

$B
[1] "a" "b"

$A
[1] 1 2 3

$B
[1] "a" "b"

$A
[1] 1 2 3

$B
[1] "a" "b"

$A
[1] 1 2 3

$B
[1] "a" "b"

Any ideas?
TIA!

Mark


???????????????????????????????????????
Mark Heckmann
Dipl. Wirt.-Ing. cand. Psych.
Vorstra?e 93 B01
28359 Bremen
Blog: www.markheckmann.de
R-Blog: http://ryouready.wordpress.com
#
Try something about like this:

split(unlist(l), rep(1:length(idx <- rapply(l, length)), idx))
On Fri, Jan 8, 2010 at 1:35 PM, Mark Heckmann <mark.heckmann at gmx.de> wrote:

  
    
#
Henrique,

thanks for the code!! It works out fine for vectors. I forgot to  
mention I also have dataframes as list elements.
Thus I want the structure of the list element to be kept intact.

I tried an recursive approach (which unfortunately resulted in some  
more code) which works.

.getNonListElements <- function(x, env){
	if(class(x)=="list") {
		for(i in seq(along=x)) .getNonListElements(x[[i]], env)	# call  
recursively
	} else {
		res <- get("res", envir = env)		# get res from other env
		res <- c(res, list(x))				# add one list element
		assign("res", res, envir=env)		# assign back to env
	}
}

flattenList <- function(l){
	res <- list()		  				# make list object
	env <- environment()  				# get current env 	
	.getNonListElements(l, env)		# search for non list elements recursively
	return(res)
}


l <- list(DF=data.frame(A=c(1,2)), vec=c("a", "b"))
l <- list(l,l)

 > flattenList(l)
[[1]]
   A
1 1
2 2

[[2]]
[1] "a" "b"

[[3]]
   A
1 1
2 2

[[4]]
[1] "a" "b"

I am not sure if one can avoid the wrapper function or still use  
rapply to simplify the code. I do not know how.
One more thing I would like to add are the objects names to the  
generated list. But I did not succeed in that.

Mark


Am 08.01.2010 um 18:29 schrieb Henrique Dallazuanna:
???????????????????????????????????????
Mark Heckmann
Dipl. Wirt.-Ing. cand. Psych.
Vorstra?e 93 B01
28359 Bremen
Blog: www.markheckmann.de
R-Blog: http://ryouready.wordpress.com