大家好,我对R来说是全新的,在开始我的项目之前,我正在尝试对简单的时间序列进行简单的时间序列分析,如下所示,存储在.csv文件中。
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)
非常感谢任何帮助。
答案 0 :(得分:3)
您可以使用read.zoo
包中的zoo
直接读取时间序列中的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
当然你可以将zoo对象转换为ts对象(即使最好使用zoo和xts包来处理时间序列):
dat.ts <- ts(dat)
答案 1 :(得分: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)