Krutik
Krutik

Reputation: 501

Convert vector with irregular time points (not dates) into an R time-series object

I am wondering if I can use the ts() functions to analyse some data where the time points are not dates.

My vector looks like this.

   0    3    5    8   12 
20.0 14.4 80.0 20.0  4.0 

I would like to convert this into a Time-Series object to make use of the ts() functions but am struggling to. I think the ts() function assumes dates as an input and my data does not have this.

Is there a method I can use to make my data look like the output from the following functions?

library(stats)
suns <- ts.intersect(lynx, sunspot.year)[, "sunspot.year"]
suns


Time Series:
Start = 1821 
End = 1934 
Frequency = 1 
  [1]   6.6   4.0   1.8   8.5  16.6  36.3 

Upvotes: 1

Views: 45

Answers (1)

G. Grothendieck
G. Grothendieck

Reputation: 269654

We can create

  • a zoo series (z). zoo generalizes ts allowing arbitrary unique times.
  • a ts series with NAs and times 0, 1, 2, 3, ..., 12 or
  • a ts series ignoring the times and using 1, 2, 3, 4, 5 for the times

with the following code:

library(zoo)
values <- c(20, 14.4, 80, 20, 4)
tt <- c(0, 3, 5, 8, 12)
z <- zoo(values, tt)
z
##    0    3    5    8   12 
## 20.0 14.4 80.0 20.0  4.0 

as.ts(z)  # fill with NAs
## Time Series:
## Start = 0 
## End = 12 
## Frequency = 1 
##  [1] 20.0   NA   NA 14.4   NA 80.0   NA   NA 20.0   NA   NA   NA  4.0

ts(values) # ignores times and uses 1:5 instead
## Time Series:
## Start = 1 
## End = 5 
## Frequency = 1 
## [1] 20.0 14.4 80.0 20.0  4.0

Upvotes: 2

Related Questions