解决办法是从stackoverflow上面看到,我来翻译成中文,并加上实际的例子应用。

创建data.table

library(data.table)
library(zoo)
dt <- data.table(
  mydates = as.Date("2012-01-01") + 1:9, 
  value1 = sort(rpois(9, 6)),
  value2 = sort(rpois(9, 6)),
  value3 = sort(rpois(9, 6)),
  value4 = sort(rpois(9, 6)),
  value5 = sort(rpois(9, 6)))

#查看数据结构
> dt
      mydates value1 value2 value3 value4 value5
1: 2012-01-02      4      4      2      2      1
2: 2012-01-03      4      4      3      5      4
3: 2012-01-04      4      4      4      5      5
4: 2012-01-05      5      5      4      5      5
5: 2012-01-06      5      5      5      6      5
6: 2012-01-07      7      6      7      6      6
7: 2012-01-08      8      8      9      7      8
8: 2012-01-09     10      8      9      9      9
9: 2012-01-10     13      9     10     10     11
> str(dt)
Classes ‘data.table’ and 'data.frame':    9 obs. of  6 variables:
 $ mydates: Date, format: "2012-01-02" "2012-01-03" ...
 $ value1 : int  4 4 4 5 5 7 8 10 13
 $ value2 : int  4 4 4 5 5 6 8 8 9
 $ value3 : int  2 3 4 4 5 7 9 9 10
 $ value4 : int  2 5 5 5 6 6 7 9 10
 $ value5 : int  1 4 5 5 5 6 8 9 11
 - attr(*, ".internal.selfref")=<externalptr> 

转化为zoo格式,提取特定日期数据

基本用法:

zoo(x,index(x))
window(zoo_object, start = as.Date("2003-02-01"), end = as.Date("2003-03-01"))`

这里需要注意的是x为向量、矩阵和 转化才能转化为zoo;而window函数的操作对象必须是zoo格式的.
参考data.table的用法 x[i, j, by, keyby, with = TRUE, ...],默认列是被当做变量,但是通过with=FALSE可以变成一列向量,用于动态选取列,但是返回结果还是data.table的格式。

x[i, j, by, keyby, with = TRUE, ...], By default with=TRUE and j is evaluated within the frame of x; column names can be used as variables. When with=FALSE j is a character vector of column names or a numeric vector of column positions to select, and the value returned is always a data.table. with=FALSE is often useful in data.table to select columns dynamically.

zooObj <- zoo(dt[,-1,with=FALSE],dt$times)
window(zooObj,start = as.Date("2012-01-05"), end = as.Date("2012-01-08"))

这样就可以提取特定日期内的数据了。但是,需要注意的是index必须是唯一的,这里的dt$times要唯一才能顺利运行。如果数据量大的话,如果粒度能到秒就ok了;或者groupby 一下,然后再作为索引。
关于这个问题,我还没有想好解决方案,待补充。


BruceZhaoR
80 声望6 粉丝

数据攻城狮


引用和评论

0 条评论