Skip to content
Prev 205841 / 398506 Next

how to flatten a list to the same level?

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