2013-04-08 113 views
1

您好,我对R完全陌生,在开始我的项目之前我正在试验简单的时间序列分析,如下所示,存储在.csv文件中。如何在R中创建时间序列变量

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 

从这个.csv文件我想创建一个时间序列变量。以下代码会产生错误。是否可能需要安装软件包?

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

任何帮助将不胜感激。

回答

3

您可以使用read.zoozoo包直接读取您的CSV时间序列。

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 

当然你也可以在动物园的对象转换为TS一个(甚至是更好地与动物园和XTS包上班的时间序列):

dat.ts <- ts(dat) 
+0

感谢这有助于一个巨大的交易被打约与包以及其它时间序列工具希望我现在可以开始我的项目! – 2013-04-11 06:28:10

1

另一种方法是使用包“Lubridate ”。

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

假设您的数据存储在一个名为'timeseries'的csv中,数据被读入data.frame。第一列更改为类POSIXct。 POSIXct在R中被广泛用作日期/时间格式。

当然,也可以将data.frame转换成TS:

timeseries <- as.ts(timeseries)