How to change the format of the index of each zoo element of a list using (x)apply

StackOverflow https://stackoverflow.com/questions/22869280

  •  27-06-2023
  •  | 
  •  

Question

Here's the setup:

    x.date <- as.Date((paste(2003, c(1, 3, 7, 9, 12), 2, sep = "-"))
    x <- zoo(rnorm(5), x.date)
    y.date <- as.Date(paste(2005, c(2, 4, 8, 10, 11), 2, sep = "-"))
    y <- zoo(rnorm(5), y.date)
    xy.list<-list(x,y) 
    xy.list 
    [[1]] 2003-01-02 2003-03-02 2003-07-02 2003-09-02 2003-12-02  
          -1.4804701  0.5280618  0.4619898 -0.5840212 -2.1988442


    [[2]] 2005-02-02 2005-04-02 2005-08-02 2005-10-02 2005-11-02 
          0.82720055 -0.05713144 0.29355203 1.08244510 -1.14746500

Here's the answer with a for-loop:

        for (i in 1:length(index(xy.list))){
  index(xy.list[[i]])<-as.yearmon(index(xy.list[[i]])) 
}    

 xy.list 
    [[1]] Jan 2003   Mar 2003   Jul 2003   Sep 2003   Dec 2003 
         -1.4804701 0.5280618 0.4619898 -0.5840212 -2.1988442


    [[2]] Feb 2005   Apr 2005   Aug 2005   Oct 2005   Nov 2005 
         0.82720055 -0.05713144 0.29355203 1.08244510 -1.14746500

My question is how to use lapply, or possibly mapply, to achieve the same end.

I've tried:

lapply(xy.list, function(list,listIdx) 
  {index(list[[listIdx]]} <- as.yearmon(index(list[[listIdx]]))}, 
xy.list, 
index(xy.list))

with the following error: 'Error in FUN(X[[1L]], ...) : unused argument (1:2)'

It appears I'm not getting something into the anonymous function that I think I am.

Was it helpful?

Solution

zoo series should have unique index values so if you are going to convert from Date to yearmon then the series should be aggregated to keep the index values unique. For example,

lapply(xy.list, aggregate, as.yearmon, mean)

or

lapply(xy.list, aggregate, as.yearmon, function(x) x[1])

Another possibility if its important not to aggregate is to convert it to an xts series:

library(xts)
lapply(xy.list, function(x) xts(coredata(x), as.yearmon(index(x))))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top