简体   繁体   English

将时间序列乘以R中的一个因子

[英]Multiply a timeseries by a factor in R

I have the following time series: 我有以下时间序列:

ts <- cbind(data.frame(date=seq(as.Date("2017/11/01"), by = "day", length.out = 30)),value=rep(5,30))
ts <- ts[order(ts$date, decreasing=T),]

I would like to adjust it by the below cumulative factor that has a value on some given dates: 我想通过以下在某些给定日期具有值的累积因子进行调整:

cf <- cbind(data.frame(date=as.Date(c("2017/11/28", "2017/11/25","2017/11/04","2017/09/25"))),cumfactor=c(0.8,0.7,0.6,.05))

Such that, the value on each date on ts will be multiplied (adjusted) by the cumfactor on cf on the corresponding date and that cumfactor will be used for subsequent (earlier) dates until the next cumfactor shows up for an earlier date. 这样,ts上每个日期的值将乘以(调整)相应日期上cf的累积因子,并且该累积因子将用于后续(较早)日期,直到下一个累积因子显示较早的日期为止。 The first (latest) dates in ts should not be adjusted if they are later than the first (latest) cumfactor date. 如果ts中的第一个(最新)日期晚于第一个(最新)cumcum日期,则不应对其进行调整。

I am looking for the following result: 我正在寻找以下结果:

result <- cbind(data.frame(date=seq(as.Date("2017/11/01"), by = "day", length.out = 30)),value=c(3,3,3,3,3.5,3.5,3.5,3.5,3.5,3.5,3.5,3.5,3.5,3.5,3.5,3.5,3.5,3.5,3.5,3.5,3.5,3.5,3.5,3.5,3.5,4,4,4,5,5))
result <- result[order(result$date, decreasing=T),]

My guess is that a for loop could be the best option but I haven't been successful at obtaining this result. 我的猜测是for循环可能是最好的选择,但我并未成功获得此结果。

Merge ts and cf, carry forward the factors and multiply them. 将ts和cf合并,继续进行因子乘积。

library(zoo)

m <- merge(ts, cf, all.x = TRUE)[nrow(ts):1, ]
transform(m, value = value * na.fill(na.locf0(cumfactor), 1))

We have retained your descending sequence of dates from the question but note that in R normally time series are represented in ascending order of date. 我们保留了您从问题中降序排列的日期的顺序,但请注意,在R中,时间序列通常以日期的升序表示。

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

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