0

I need to read a data series stored in a .csv in R and analyze it using the library TSstudio. This data series consists of two columns, the first one stores the date, the second one stores a floating point value measured daily. As straightforward as it could get.

So I first read the csv as a data.frame:

a_data_frame <- read.csv("some_data.csv", sep=";", dec = ",", col.names=c("date", "value"))
head(a_data_frame)

A data.frame: 6 × 2
    date        value
    <chr>       <dbl>
1   04/06/1986  0.065041
2   05/06/1986  0.067397
3   06/06/1986  0.066740
4   09/06/1986  0.068247
5   10/06/1986  0.067041
6   11/06/1986  0.066740

The values in the first column are of type char, so I convert them to date thanks to the library lubridate:

library(lubridate)
a_data_frame$date <- dmy(a_data_frame$date)
head(a_data_frame)

A data.frame: 6 × 2
    date        value
    <date>      <dbl>
1   1986-06-04  0.065041
2   1986-06-05  0.067397
3   1986-06-06  0.066740
4   1986-06-09  0.068247
5   1986-06-10  0.067041
6   1986-06-11  0.066740

Here comes my headache. When I try to convert the data.frame to time series, I get a matrix of type character instead:

a_time_series <- as.ts(a_data_frame)
head(a_time_series)

A matrix: 6 × 2 of type chr
    date    value
1986-06-04  0.065041
1986-06-05  0.067397
1986-06-06  0.066740
1986-06-09  0.068247
1986-06-10  0.067041
1986-06-11  0.066740

Is there any other way to convert a data.frame to a ts object?

Francesco Ghizzo
  • 57
  • 1
  • 1
  • 6

1 Answers1

1

Assuming some_data.csv generated reproducibly in the Note read it into a zoo series and then use as.ts. That gives a daily series with NA's for the missing days and the time being the number of days since the Epoch. That may or may not be the ts object you want but the question did not specify it further. Also see this answer.

library(zoo)
z <- read.csv.zoo("some_data.csv", format = "%d/%m/%Y")
tt <- as.ts(z); tt
## Time Series:
## Start = 5998 
## End = 6005 
## Frequency = 1 
## [1] 0.065041 0.067397 0.066740       NA       NA 0.068247 0.067041 

0.066740

Note

Lines <- "date,value
04/06/1986,0.065041
05/06/1986,0.067397
06/06/1986,0.066740
09/06/1986,0.068247
10/06/1986,0.067041
11/06/1986,0.066740"
cat(Lines, file = "some_data.csv")
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341