0

I have a matrix with 24 time series which looks like:

                    Ta.f Ta.f Ta.f Ta.f
1995-10-13 04:00:00 13.6 13.6 13.6 13.6
1995-10-13 05:00:00 13.6 13.6 13.6 13.6
1995-10-13 06:00:00 13.6 13.6 13.6 13.6
1995-10-13 07:00:00 13.5 13.5 13.5 13.5
1995-10-13 08:00:00 13.5 13.5 13.5 13.5

I would like to use the apply() function to every column to difference according the index of the column. So column 1 needs diff(x,), column 2 needs diff(x,lag=2) and so on. What I have done is that:

trans_temp <- apply(temp_mat,MARGIN=2,diff)

Which returns a matrix in which all time series are differenced once. Any recommendation?

xlecoustillier
  • 16,183
  • 14
  • 60
  • 85
JPV
  • 1,079
  • 1
  • 18
  • 44
  • IIUC, you can use `xts::Lag` which accepts a vector for it's `k` argument. But, since your code isn't reproducible, I didn't try – GSee Apr 24 '13 at 14:51

1 Answers1

3

Try this:

trans_temp <- lapply(seq(ncol(temp_mat)), function(z) diff(temp_mat[,z], lag=z))

Note that the individual vectors of diffs have different lengths due to the different lags.

sieste
  • 8,296
  • 3
  • 33
  • 48
  • Which is the difference between lapply and apply? – JPV Apr 24 '13 at 14:29
  • @R_user: `lapply` applies the `function(z)` to each element of a list (here 1,2,...,ncol(temp_mat)), while `apply` can be used for matrices, accepting a `MARGIN` argument – sieste Apr 24 '13 at 14:32