2015-10-14 50 views
0

我是R新手,我正在尝试使用预测库使用GA连接进行一些预测。在R中指定时间系列

我有一个这样的输入数据:

day month year visits 
1 01 01 2013 21821 
2 02 01 2013 17865 
3 03 01 2013 25300 
4 04 01 2013 41184 
5 05 01 2013 48953 
6 06 01 2013 64135 

它吸引每月和每年的天访问。

当我尝试使用TS功能我是这样的:

visits.ts = TS(ga.data $访问,开始= C(2013,1),结束= C(2014,1)频率= 12)

由于输出是这样的:

 Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec 
2013 
2014 

这里是我的question-我怎么能分裂月至数天,创建这样一个输出:

 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 
January 2013 
February 2013 
+0

所以我需要不创建预后一个月,但一天 – HalfPintBoy

+0

看到[评论](https://stackoverflow.com/questions/8437620/analyzing-daily-weekly-data-using-ts-in-r) - 你最好使用'动物园'或' xts'用于日常数据 – jeremycg

回答

1

首先创建一些测试数据,DF。 (今后请提供的测试数据。)

# create data set for testing 
tt0 <- seq(as.Date("2013-01-01"), as.Date("2014-12-31"), by = "day") 
lt <- as.POSIXlt(tt0) 
DF <- data.frame(year = lt$year + 1900, month = lt$mon + 1, day = lt$mday, visits = 1:730) 

下,关键取决于包含完全相同的天数(即没有闰年)每年。幸运的是,问题中显示的数据就是这种情况。使用DF其转换为"ts"类:

# convert to ts 
tser <- ts(DF$visits, start = 2013, freq = 365) 

如果我们确实有闰年,我们可能要使用从动物园包"zoo"类或"xts"类从XTS包。

对于第二个问题,第一附加一个year_month柱,然后使用dcast来创建2D显示:

library(reshape2) 
DF2 <- transform(DF, year_month = I(sprintf("%d-%02d", year, month))) 
dcast(DF2, year_month ~ day, value.var = "visits") 

或使用as.yearmon从动物园包:

library(reshape2) 
library(zoo) 
DF2 <- transform(DF, year_month = as.yearmon(paste(year, month, sep = "-"))) 
dcast(DF2, year_month ~ day, value.var = "visits") 

,这里是一个第三种选择。这其中不使用任何外部包,虽然这是一个有点慢:

DF2 <- transform(DF, day = factor(day), year_month = sprintf("%d-%02d", year, month)) 
xtabs(visits ~ year_month + day, DF2, sparse = TRUE) 

省略sparse=TRUE它会更快,但将填补未使用的斑点0