Question

I'm having some trouble with lists, and unlist() doesn't seem to cut it.

Here's the problem: I execute a function over a list using lapply(). This function splits up xts objects by certain criteria, thus it returns a list of two xts objects. The resulting list of the lapply() consists of multiple sub-lists (in my example: the output looks a lot like list.2)

Example:

library(xts)

#create three dummy xts objects
a<-c(1:10)
b<-c(2:5)
c<-c(6:9)

a.by<-as.POSIXct(a, tz="GMT", origin="1990-01-01 00:00:00")
b.by<-as.POSIXct(b, tz="GMT", origin="1990-01-01 00:00:00")
c.by<-as.POSIXct(c, tz="GMT", origin="1990-01-01 00:00:00")

xts.a<-xts(a, order.by=a.by)
xts.b<-xts(b, order.by=b.by)
xts.c<-xts(c, order.by=c.by)

# creating first list of objects a & b. this is passed to my function

list.1<-list(xts.a, xts.b)

# creating second list of objects a & b, c. this is similar to my output

list.2<-list(list.1, xts.c)

Goal: I want to pass these xts objects on to further functions. I require a list of all xts objects in the main list and in all the sub-lists. In my example I'd like list(xts.a, xts.b, xts.c). I would like to subset the sub-list, break it and the main list up and relist with the parts (xts objects).

Problems: Due to the data load, I'm trying to do this automaticly, not just the problem above. So for more then one sub-list and not specificly in this order, or with just three objects in the list.

Thoughts: I've tried working with class() -> list.2[class(list.2)=="list"]

Creating subsetting vectors (this seems to have worked best so far) -> subset_vector<-lapply(list.2, class) and then using this vector (plus a sequence) to pick out the lists -> list.2[[sequence[subset_vector=="list"]]]

But this all seems way too complicated, there must be an easier solution?

Thanks in advance for your help!

Ben

Was it helpful?

Solution

c(list.2[sapply(list.2, is.xts)], unlist(list.2[!sapply(list.2, is.xts)], recursive=F))

Is this what you were looking for?

OTHER TIPS

You can write a recursive function like this :

LL <- vector('list')
rapply2 <- function(x) {
 for(i in seq_along(x)) {
    if (is.xts(x[[i]])) 
      LL <<- append(LL,list(x[[i]]))
     else rapply2(x[[i]])
  }
}

Then

rapply2(list.2)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top