Question

Hi there I am completely new to R and before I start my project I am trying out simple time series analyses upon a simple time series as follows which is stored in a .csv file.

Date/Time,AT
01-Jan-2008 00:00,1
01-Jan-2008 01:00,2
01-Jan-2008 02:00,3
01-Jan-2008 03:00,4
01-Jan-2008 04:00,5
01-Jan-2008 05:00,4
01-Jan-2008 06:00,3
01-Jan-2008 07:00,2
01-Jan-2008 08:00,1
01-Jan-2008 09:00,2
01-Jan-2008 10:00,3
01-Jan-2008 11:00,4
01-Jan-2008 12:00,5

from this .csv file I would like to create a time series variable. The following code produces errors. Is it likely i will require a package to install?

test=ts(scan("desktop/test.csv"),frequency=13, start=2008+1/1)

Any help would be greatly appreciated.

Was it helpful?

Solution

You can use read.zoo from zoo package to read directly you csv in a time series.

library(zoo)

fmt <- '%d-%b-%Y %H:%M'

## if data in file replace with this line:
## dat <- read.zoo("myfile.dat",header=TRUE,sep=',',tz='',format=fmt,index=0:1)                     

dat <- read.zoo(text='Date/Time,AT
01-Jan-2008 00:00,1
01-Jan-2008 01:00,2
01-Jan-2008 02:00,3
01-Jan-2008 03:00,4
01-Jan-2008 04:00,5
01-Jan-2008 05:00,4
01-Jan-2008 06:00,3
01-Jan-2008 07:00,2
01-Jan-2008 08:00,1
01-Jan-2008 09:00,2
01-Jan-2008 10:00,3
01-Jan-2008 11:00,4
01-Jan-2008 12:00,5',header=TRUE,sep=',',
                tz='',
                format=fmt,       ## date format
                index=0:1)        ## rownames + first column

dat
2008-01-01 00:00:00 2008-01-01 01:00:00 2008-01-01 02:00:00 2008-01-01 03:00:00 2008-01-01 04:00:00 2008-01-01 05:00:00 
                  1                   2                   3                   4                   5                   4 
2008-01-01 06:00:00 2008-01-01 07:00:00 2008-01-01 08:00:00 2008-01-01 09:00:00 2008-01-01 10:00:00 2008-01-01 11:00:00 
                  3                   2                   1                   2                   3                   4 
2008-01-01 12:00:00 
                  5 

Of course you can convert the zoo object to ts one (even it is better to work with zoo and xts package for time series):

dat.ts <- ts(dat)

OTHER TIPS

An alternative is to use package 'Lubridate'.

library(lubridate)
timeseries <- read.table("timeseries.csv", sep=",", header=T, dec=".")
timeseries[,1] <- dmy_hm(timeseries[,1])

Assuming your data is stored in a csv called 'timeseries', the data is read into a data.frame. The first column is changed into class POSIXct. POSIXct is widely used in R as date/time format.

Of course it is also possible to convert the data.frame into ts:

timeseries <- as.ts(timeseries)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top