繁体   English   中英

动物园系列子集不在系列中

[英]Subsetting zoo series by a time that is not in the series

R中是否有一个好的包允许按时间序列中的时间子集(即索引)时间序列? 例如,对于金融应用程序,通过不在数据库中的时间戳索引价格序列,应该在时间戳之前返回最新的可用价格。

在代码中,这就是我想要的

n =15
full.dates = seq(Sys.Date(), by = 'day', length = n)
series.dates = full.dates[c(1:10, 12, 15)] 
require(zoo)
series=zoo(rep(1,length(series.dates)), series.dates)
series[full.dates[11]]

这回来了

Data:
numeric(0)

Index:
character(0)

但是,我希望在full.dates [11]之前返回最后一个现有日期的值,即full.dates [10]:

series[full.dates[10]]
2014-01-03 
     1 

谢谢

您可以使用index来提取zoo对象中的观察索引。 然后,索引可用于对对象进行子集化。 一步一步地显示逻辑(如果我理解正确的话,你只需要最后一步):

# the index of the observations, here dates
index(series)

# are the dates smaller than your reference date?
index(series) < full.dates[11]

# subset observations: dates less than reference date
series[index(series) < full.dates[11]]

# select last observation before reference date:
tail(series[index(series) < full.dates[11]], 1)

# 2014-01-03 
#          1

一个可能的选择是,扩大你的时间序列“replac [E]每个NA与最近的非NA”使用na.locfxout说法(见?na.locf?approx这个答案

# expand time series to the range of dates in 'full.dates'
series2 <- na.locf(series, xout = full.dates)
series2

# select observation at reference date
series2[full.dates[10]]
# 2014-01-03 
#          1

如果您希望将不完整系列中的缺失值替换为“向后观察后退”,则需要merge系列与包含所需连续日期范围的“虚拟”动物园对象merge

series3 <- merge(series, zoo(, full.dates))
na.locf(series3, fromLast = TRUE)

na.locf(x, xout = newdate)看起来并不比下标差,但无论如何我们定义了一个名为"zoo2"的子类"zoo" "zoo2" ,其中[使用na.locf 这是一个未经测试的最小实现,但可以扩展:

as.zoo2 <- function(x) UseMethod("as.zoo2")
as.zoo2.zoo <- function(x) structure(x, class = c("zoo2", setdiff(class(x), "zoo2")))
"[.zoo2" <- function(x, i, ...) {
    if (!missing(i) && inherits(i, class(index(x)))) {
        zoo:::`[.zoo`(na.locf(x, xout = i),, ...)
    } else as.zoo2(zoo:::`[.zoo`(x, i, ...))
}

这给出了:

> series2 <- as.zoo2(series)
> series2[full.dates[11]]
2014-01-04 
         1 

我坚决认为,如果所需的索引值不存在,该子集函数应该返回前行。 子集函数应该返回用户请求的内容; 他们不应该假设用户想要的东西与他们要求的不同。

如果这是想要的,您可以使用if语句轻松地处理它。

series.subset <- series[full.dates[11]]
if(NROW(series.subset)==0) {
  # merge series with an empty zoo object
  # that contains the index value you want
  prior <- merge(series, zoo(,full.dates[11]))
  # lag *back* one period so the NA is on the prior value
  prior <- lag(prior, 1)
  # get the index value at the prior value
  prior <- index(prior)[is.na(prior)]
  # subset again
  series.subset <- series[prior]
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM