use*_*153 6 aggregate r time-series
我不经常在R中使用日期,但我想这很容易.我有几个年的日常数据和一些数值,我希望每8天得到相关值的总和.什么是最好的方法?
您将提供的任何帮助将不胜感激!
str(temp)
'data.frame':648 obs. of 2 variables:
$ Date : Factor w/ 648 levels "2001-03-24","2001-03-25",..: 1 2 3 4 5 6 7 8 9 10 ...
$ conv2: num -3.93 -6.44 -5.48 -6.09 -7.46 ...
head(temp)
Date amount
24/03/2001 -3.927020472
25/03/2001 -6.4427004
26/03/2001 -5.477592528
27/03/2001 -6.09462162
28/03/2001 -7.45666902
29/03/2001 -6.731540928
30/03/2001 -6.855206184
31/03/2001 -6.807210228
1/04/2001 -5.40278802
Run Code Online (Sandbox Code Playgroud)
我试图使用聚合函数,但由于某些原因它不起作用,它以错误的方式聚合:
z <- aggregate(amount ~ Date, timeSequence(from =as.Date("2001-03-24"),to =as.Date("2001-03-29"), by="day"),data=temp,FUN=sum)
Run Code Online (Sandbox Code Playgroud)
我喜欢xts这种操作的包装.
我读了你的数据,作为动物园对象.看格式选项的灵活性.
library(xts)
ts.dat <- read.zoo(text ='Date amount
24/03/2001 -3.927020472
25/03/2001 -6.4427004
26/03/2001 -5.477592528
27/03/2001 -6.09462162
28/03/2001 -7.45666902
29/03/2001 -6.731540928
30/03/2001 -6.855206184
31/03/2001 -6.807210228
1/04/2001 -5.40278802',header=TRUE,format = '%d/%m/%Y')
Run Code Online (Sandbox Code Playgroud)然后我提取给定时期的索引
ep <- endpoints(ts.dat,'days',k=8)
Run Code Online (Sandbox Code Playgroud)最后我将我的函数应用于每个索引的时间序列.
period.apply(x=ts.dat,ep,FUN=sum )
2001-03-29 2001-04-01
-36.13014 -19.06520
Run Code Online (Sandbox Code Playgroud)cut()在aggregate()命令中使用.
一些样本数据:
set.seed(1)
mydf <- data.frame(
DATE = seq(as.Date("2000/1/1"), by="day", length.out = 365),
VALS = runif(365, -5, 5))
Run Code Online (Sandbox Code Playgroud)
现在,聚合.详情?cut.Date请见.您可以使用以下方法指定每个组中所需的天数cut:
output <- aggregate(VALS ~ cut(DATE, "8 days"), mydf, sum)
list(head(output), tail(output))
# [[1]]
# cut(DATE, "8 days") VALS
# 1 2000-01-01 8.242384
# 2 2000-01-09 -5.879011
# 3 2000-01-17 7.910816
# 4 2000-01-25 -6.592012
# 5 2000-02-02 2.127678
# 6 2000-02-10 6.236126
#
# [[2]]
# cut(DATE, "8 days") VALS
# 41 2000-11-16 17.8199285
# 42 2000-11-24 -0.3772209
# 43 2000-12-02 2.4406024
# 44 2000-12-10 -7.6894484
# 45 2000-12-18 7.5528077
# 46 2000-12-26 -3.5631950
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6954 次 |
| 最近记录: |