2013-05-29 63 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

這解釋了不好的滯後行爲。感謝您的澄清和建議。 –