R how to generate a time series?

5

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

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

    
asked by anonymous 03.10.2015 / 01:00

1 answer

3

The ts class object will not understand your date column. Instead, try to convert it to some number.

Something like:

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

To create your ts object you only need to use the values 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, ts is not very good for daily data, since the frequency is not fixed (it has year with 365 and year with 364 days).

Anyway, if you only do manipulations and graphics with the series not transforming it into ts , use only the lubridate functions combined with dplyr and ggplot2 .

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

> library(xts)
> st <- xts(dados$valor, dados$data)
> st
           [,1]
2014-01-01    1
2014-01-02    2
2014-01-03    3
    
03.10.2015 / 01:31