【发布时间】:2013-09-01 00:40:27
【问题描述】:
问题:给定一个向量,我想知道一系列累积和的最小值,其中每个累积和是针对向量的递增起始索引和固定结束索引(1 :5, 2:5, ..., 5:5)。具体来说,我想知道是否可以使用for() 循环来计算这是否可以计算,以及该算法/计算是否有潜在的术语。我在 R 工作。
上下文:感兴趣的向量包含压力变化的时间序列。我想知道在一系列起点但终点固定的压力的最大(或最小)净变化。
详情+示例:
#Example R code
diffP <- c(0, -1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0)
minNet1 <- min(cumsum(diffP))
minNet1 #over the whole vector, the "biggest net drop" (largest magnitude with negative sign) is -1.
#However, if I started a cumulative sum in the second half of diffP, I would get a net pressure change of -2.
hold <- list()
nDiff <- length(diffP)
for(j in 1:nDiff){
hold[[j]] <- cumsum(diffP[j:nDiff])
}
answer <- min(unlist(hold)) #this gives the answer that I ultimately want
希望我上面的例子有助于阐明我的问题。 answer 包含正确答案,但我宁愿在 R 中没有 for() 循环的情况下执行此操作。是否有更好的方法来进行此计算,或者我可以为其命名?
【问题讨论】:
标签: r algorithm time-series cumulative-sum