[R] Re-sort list of vectors

Jan Hummel Hummel at mpimp-golm.mpg.de
Tue Aug 16 13:06:33 CEST 2005


Dear list members,

thank all of you for replying to my question. Finally I came up with 3
working solutions, which I ask you to rank now in terms of used
resources, computation speed, "design questions" etc. 

x <- list("1" = c(a = 1, b = 2, c = 3), "2" = c(d = 4, b = 5, e = 6))

#looping; Thanks to Jim Holtman
solution1<-function(x){
	Result <- list()
	for (i in names(x)){
		for (j in names(x[[i]])){
			Result[[j]][[i]] <- x[[i]][[j]]
		}
	}
	return(Result)
}

#lapplying function within function; derived from Solution1
solution2<-function(x){
	temporaryList <- list()
	
lapply(names(x),function(y){lapply(names(x[[y]]),function(z){temporaryLi
st[[z]][[y]]<<-x[[y]][[z]]})})
	return(temporaryList)
}

#vectorized; Thanks to Dimitris Rizopoulos
solution3<-function(x){
	y <- data.frame(name = rep(names(x), sapply(x, length)), value =
unlist(x))
	lapply(split(y, unlist(lapply(x, names))), function(z){ res <-
z$value; names(res) <- z$name; return(res) })
}

I would prefer solution2(), because ... I don't know.

Thanks in advance!
	Jan




More information about the R-help mailing list