0

unfortunately I have a problem and hope anybody has an idea.

I want to use the first difference for some time series.

I have a Datamatrix with 100 columns. Every is a timeseries.

For example I can create with: v <-diff(DM$column1) a new vector with my wanted result.

But is it possible to take more as one column? For example from $column1 until $column30.

And can I overwrite the columns with the new values directly in the original DM matrix?

Thank you very much for any ideas.

Best regards

1 Answers1

0

You can use apply to apply the function diff to each column.

Let's take an example matrix representing 5 time series

set.seed(1)
m <- `colnames<-`(replicate(5, rnorm(10)), LETTERS[1:5])

m
#>                A           B           C           D          E
#>  [1,] -0.6264538  1.51178117  0.91897737  1.35867955 -0.1645236
#>  [2,]  0.1836433  0.38984324  0.78213630 -0.10278773 -0.2533617
#>  [3,] -0.8356286 -0.62124058  0.07456498  0.38767161  0.6969634
#>  [4,]  1.5952808 -2.21469989 -1.98935170 -0.05380504  0.5566632
#>  [5,]  0.3295078  1.12493092  0.61982575 -1.37705956 -0.6887557
#>  [6,] -0.8204684 -0.04493361 -0.05612874 -0.41499456 -0.7074952
#>  [7,]  0.4874291 -0.01619026 -0.15579551 -0.39428995  0.3645820
#>  [8,]  0.7383247  0.94383621 -1.47075238 -0.05931340  0.7685329
#>  [9,]  0.5757814  0.82122120 -0.47815006  1.10002537 -0.1123462
#> [10,] -0.3053884  0.59390132  0.41794156  0.76317575  0.8811077

Then to diff each column all at once, we can do:

apply(m, 2, diff)
#>                A           B           C           D           E
#>  [1,]  0.8100971 -1.12193793 -0.13684107 -1.46146728 -0.08883808
#>  [2,] -1.0192719 -1.01108382 -0.70757132  0.49045934  0.95032506
#>  [3,]  2.4309094 -1.59345931 -2.06391668 -0.44147665 -0.14030018
#>  [4,] -1.2657730  3.33963081  2.60917744 -1.32325452 -1.24541889
#>  [5,] -1.1499762 -1.16986453 -0.67595449  0.96206499 -0.01873946
#>  [6,]  1.3078974  0.02874335 -0.09966677  0.02070461  1.07207712
#>  [7,]  0.2508957  0.96002647 -1.31495688  0.33497656  0.40395096
#>  [8,] -0.1625434 -0.12261502  0.99260233  1.15933877 -0.88087914
#>  [9,] -0.8811697 -0.22731987  0.89609162 -0.33684962  0.99345394

Note that when you diff a vector, the result is one element shorter, so this matrix is one row shorter than the original.

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87