如何使用(x)apply更改列表中每个zoo元素的索引格式

时间:2014-04-04 17:30:03

标签: r apply

以下是设置:

    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

以下是for循环的答案:

        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

我的问题是如何使用lapply或者mapply来达到同样的目的。

我试过了:

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

出现以下错误:'Error in FUN(X[[1L]], ...) : unused argument (1:2)'

看来我没有得到我认为我的匿名函数。

1 个答案:

答案 0 :(得分:0)

动物园系列应该有唯一的索引值,因此如果要将Date从Date转换为yearmon,则应该聚合该系列以保持索引值唯一。例如,

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

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

如果重要的是不聚合的另一种可能性是将其转换为xts系列:

library(xts)
lapply(xy.list, function(x) xts(coredata(x), as.yearmon(index(x))))