apply
coerces its first argument to a plain array so zoo is no longer involved. Perhaps you want this:
> diff(tmp)
2 1 0
3 -1 1
or this
> diff(tmp, na.pad = TRUE)
x.1 x.2
1 NA NA
2 1 0
3 -1 1
Question
Below is example code of the issue I am having. It seems that zoo does not work with apply. Any suggestions on how to make this work as desired?
> #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
Solution
apply
coerces its first argument to a plain array so zoo is no longer involved. Perhaps you want this:
> diff(tmp)
2 1 0
3 -1 1
or this
> diff(tmp, na.pad = TRUE)
x.1 x.2
1 NA NA
2 1 0
3 -1 1