phaser phaser - 1 month ago 10
R Question

`pracma`: collapse the matrix result of `detrend` for a single time series

I am using the

co2
data in R. I began by using
detrend()
. It seems to have worked, but it out putted the data in a time series format that R functions I try to use later on think it is a multivariate time series rather than a single. I want to keep it as a univariate time series. Here is my code. I have tried changing the data's format with no luck.

data(co2)
co2
plot(co2)

dmn <- list(month.abb, unique(floor(time(co2))))
co2.m <- matrix(co2, 12, dimnames = dmn)

co2.dt <- pracma::detrend(co2.m, tt = 'linear')
co2.dt <- t(co2.dt)
co2.dt


Here is one of the errors I get:

plot.ts(co2.dt)



Error in plotts(x = x, y = y, plot.type = plot.type, xy.labels = xy.labels, :
cannot plot more than 10 series as "multiple"


Using
ts.plot
will get it to plot but it thinks it is a multivariate time series.

I would like it to plot as a single time series the way
co2
plots. Ideally I would like to change the format of
co2.dt
to the format of
co2
.

str(co2)
Time-Series [1:468] from 1959 to 1998: 315 316 316 318 318 ...

str(co2.dt)
Time-Series [1:39, 1:12] from 1959 to 1997: -1.74 -2.11 -2.11 -2.11 -1.99 ...
- attr(*, "dimnames")=List of 2
..$ : NULL
..$ : chr [1:12] "Jan" "Feb" "Mar" "Apr" ...


They are both time series but slightly different and that difference seems to be disrupting a lot of the functions I try to use later on.

Answer

I would like it to plot as a single time series the way co2 plots

co2.dt <- pracma::detrend(co2.m, tt = 'linear')
co2.dt <- ts(as.numeric(co2.dt), start = c(1959,1), frequency=12)

str(co2.dt)
# Time-Series [1:468] from 1959 to 1998: -1.741 -0.608 -0.176 1.127 1.94 ...

plot.ts(co2.dt)

enter image description here


Original Answer (on why plot.ts fails to work)

The problem is that plot.ts will plot multiple time-series on a panel, rather than on a single graph. Then there is a maximum number of series that R can handle easily. The error message tells you that more than 10 series is not supported, while you have 12 (because after transposition you are looking at yearly data for each of 12 months). Use ts.plot instead:

ts.plot(co2.dt)

If you don't like ts.plot, then you need to split your time series into several groups, each on a new graphical window. For example, you can plot month 1-6 on one window, and month 7-12 on another.

plot.ts(co2.dt[,1:6])
x11(); plot.ts(co2.dt[,7:12])