Skip to content

Unlisting while preserving object types?

1 message · Jim Lemon

#
"Turner, Jason" wrote:
I don't find unpacking lists straightforward, and use recursion when I
need a general solution. That is, to say, I test each component of a
list, and if it is another list, I call the function with the sublist.
At the bottom list, I apply the appropriate function and return the
transformed data. For a toy example...

# list2mat unpacks a list of vectors, possibly nested, and 
# returns a matrix whose columns are the vectors in the list.
# Note that the vectors in the list must all be the same length.

list2mat<-function(input.list) {
 firstname<-""
 for(l in 1:length(input.list)) {
  if(is.list(input.list[[l]])) {
   if(exists("newmat",inherits=F)) {
    if(nchar(firstname)) {
     tempnames<-firstname
     firstname<-""
    }
    else tempnames<-colnames(newmat)
    newmat<-cbind(newmat,list2mat(input.list[[l]]))
   }
   else {
    newmat<-list2mat(input.list[[l]])
    firstname<-names(input.list[l])
   }
  }
  else {
   if(exists("newmat",inherits=F)) {
    if(nchar(firstname)) {
     tempnames<-firstname
     firstname<-""
    }
    else tempnames<-colnames(newmat)
    newmat<-cbind(newmat,input.list[[l]])
    colnames(newmat)<-c(tempnames,names(input.list[l]))
   }
   else {
    newmat<-input.list[[l]]
    firstname<-names(input.list[l])
   }
  }
 }
 return(newmat)
}
Jim

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._