salhin
salhin

Reputation: 2654

Convert a multi-series zoo object to a list of single series zoo objects

Suppose I have the following multi-series zoo object:

X.Z <- structure(c(0, 0.01, 0.01, 0, 0, 0.01), .Dim = c(3L, 2L), .Dimnames = list(
NULL, c("FTSE100", "FTALLSH")), index = structure(c(5844, 
                                                    5845, 5846), class = "Date"), class = "zoo")

I want to convert X.Z into a list of zoo objects called FTSE100 and FTALLSH. I used the following:

X.Zs <- list()
for(i in 1:2){
    X.Zs[[i]] <- X.Z[,i]
}
names(X.Zs) <- colnames(X.Z)

Is there any 'more' efficient way than the above?

My question is the reverse of this question

Upvotes: 2

Views: 336

Answers (2)

Barker
Barker

Reputation: 2094

lapply can do it very simply

X.Zs <- lapply(X.Z,"[")

Upvotes: 2

Vandenman
Vandenman

Reputation: 3176

You could try something like this taken from this post:

X.Zs <- lapply(seq_len(dim(X.Z)[2L]), function(i) {x <- X.Z[, i]; class(x) <- 'zoo'; x})
names(X.Zs) <- dimnames(X.Z)[[2L]]

Upvotes: 0

Related Questions