2013-05-29 60 views
0

下面是我遇到的问题的示例代码。看来动物园不适用于申请。有关如何根据需要进行此项工作的任何建议?使用适用于动物园对象

> #I am trying to use apply with zoo 
> tmp <- zoo(matrix(c(0,1,0,0,0,1),nrow=3)) 
> tmp 

1 0 0 
2 1 0 
3 0 1 
> #for each column I want to subtract the lag 
> #as an example I extract 1 column 
> tmpcol <- tmp[,1] 
> #this is what I want, for each column 
> diffcol <- tmpcol-lag(tmpcol,-1) 
> diffcol 
2 3 
1 -1 
> #but if I do this using apply it gives bizarre behavior 
> z <- apply(tmp,2,function(x) x-lag(x,-1)) 
> z 
    X.1 X.2 
1 0 0 
2 0 0 
3 0 0 

回答

3

apply强制它的第一个参数为一个普通数组,所以动物园不再涉及。也许你想这样的:

> diff(tmp) 

2 1 0 
3 -1 1 

或本

> diff(tmp, na.pad = TRUE) 
    x.1 x.2 
1 NA NA 
2 1 0 
3 -1 1 
+0

这解释了不好的滞后行为。感谢您的澄清和建议。 –