R how to generate a time series?

Asked

Viewed 2,745 times

5

I would like to know how to generate a time series of a file that has two columns (date and value), but the date is in the following format yyyy-MM-dd.

When I use the ts() command, it replaces the date value with a number, for example: the date (2014-01-02) became the number (16072). It is worth mentioning that this date is the first of the file, but after the use of ts() it descends some positions, that is, all fields mixed.

  • Use xts, ts is more limited and works with regular data such as monthly data, for example.

  • Thank you, I’ll take a look.

1 answer

3


The class object ts will not understand your column of dates. On the contrary, Take try to convert it into some number.

Something like:

> as.numeric(as.Date("2014-01-02"))
[1] 16072

To create your object ts you need to use only the value column:

> dados <- read.csv2(text = '
+ "data";"valor"
+ "2014-01-01";1
+ "2014-01-02";2
+ "2014-01-03";3')
> dados$data <- as.Date(dados$data)
> st <- ts(dados$valor, start = 2014, frequency = 365)
> st
Time Series:
Start = c(2014, 1) 
End = c(2014, 3) 
Frequency = 365 
[1] 1 2 3

However, the ts is not very good for daily data, since the frequency is not fixed (has year with 365 and year with 364 days).

Anyway, if you’re just doing manipulations and graphics with the series don’t turn it into ts, use only the functions of lubridate combined with the dplyr and the ggplot2.

If you really want to convert to time series formats on R, use the package xts:

> library(xts)
> st <- xts(dados$valor, dados$data)
> st
           [,1]
2014-01-01    1
2014-01-02    2
2014-01-03    3
  • Thanks, I’ll try here.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.