您可以分別使用cummax()
和cummin()
,計算累積的最大/最小值。你只需要在白天應用這些功能。您可以通過將您的數據加入日常組,然後將以下功能應用於每個組,然後將數據重新組合到一起。
下面是使用xts包中的日常數據的可重複的示例。
library(xts)
set.seed(21)
tm <- timeBasedSeq('2017-07-14/2017-07-15/M')
x <- xts(20*cumprod(1+rnorm(length(tm), 0, 0.0025)), tm)
colnames(x) <- "price"
aggfun <- function(x) {
stopifnot(ncol(x) > 0)
# remove potential column name
colnames(x) <- NULL
r <- xts(cbind(Open = rep(x[1], nrow(x)),
High = cummax(x),
Low = cummin(x),
Close = x), index(x))
r
}
y <- do.call(rbind, lapply(split(x, "day"), aggfun))
從第一天開始輸出到下一個模樣:
y[1439:1442]
# Open High Low Close
# 2017-07-14 23:58:00 20.03965 25.02193 19.60128 23.73810
# 2017-07-14 23:59:00 20.03965 25.02193 19.60128 23.71598
# 2017-07-15 00:00:00 23.73816 23.73816 23.73816 23.73816
# 2017-07-15 00:01:00 23.73816 23.73816 23.71164 23.71164
非常感謝。在拼寫功能中有一個小錯字:天而不是日。 – PDM