對於多個時間序列變量,如何計算相對於固定年份的隨時間變化的百分比?R中的時間序列:如何計算R中多個時間序列變量的固定年份的變化百分比?
structure(list(haiarYear = 2009:2012,
anyInf = c(25914L, 23601L, 22713L, 22654L),
haiarPatDays = c(10402161L, 10289079L, 10212208L, 10033090L),
rate = c(2.49121312388839,
2.29379131018432,
2.22410276014746,
2.25792851454537)),
.Names = c("haiarYear", "anyInf", "haiarPatDays", "rate"),
row.names = c(NA, -4L),
class = "data.frame")
tsInfPatDays <- ts(tInfPatDays[,-1], start=2009)
options(digits=2)
產生一個時間序列結構,看起來像這樣:
Time Series:
Start = 2009
End = 2012
Frequency = 1
anyInf haiarPatDays rate
2009 25914 10402161 2.49
2010 23601 10289079 2.29
2011 22713 10212208 2.22
2012 22654 10033090 2.26
我想計算的相對百分比變化到2009年的每一個變量:anyInf
,haiarPatDays
和rate
。
對於一個變量,我可以計算出百分比變化爲:
transform(tsInfPatDays, since2009 = (rate-rate[1])/rate[1]*100)
產量:
anyInf haiarPatDays rate since2009
25914 10402161 2.49 0.00
23601 10289079 2.29 -7.92
22713 10212208 2.22 -10.72
22654 10033090 2.26 -9.36
以下計算相對於上一年度百分比變化和每個變量操作:
100*(tsInfPatDays/lag(tsInfPatDays, -1)-1)
給予:
Time Series:
Start = 2010
End = 2012
Frequency = 1
tsInfPatDays.anyInf tsInfPatDays.haiarPatDays tsInfPatDays.rate
2010 -8.93 -1.087 -7.92
2011 -3.76 -0.747 -3.04
2012 -0.26 -1.754 1.52
使用這個作爲一個模型,我期望能夠通過我需要通過索引2009參考數據tsInfPatDays[1,]
anyInf haiarPatDays rate
2.59e+04 1.04e+07 2.49e+00
然後執行計算:
(tsInfPatDays-tsInfPatDays[1,])/tsInfPatDays[1,]*100
第一行似乎是正確計算,但後續行顯然是錯誤的。
我已經看到了用於行減法的轉置矩陣方法。儘管不是百分比,但作爲概念證明,我試着從時間序列行中減去參考行的值。我得到了以下錯誤:
t(tsInfPatDays-t(tsInfPatDays[1,]))
Error in `-.default`(tsInfPatDays, t(tsInfPatDays[1, ])) :
non-conformable arrays
我得到同樣的錯誤,如果我嘗試使用轉置矩陣方法之前提取數據:
t(tsInfPatDays-t(drop(coredata(tsInfPatDays[1,]))))
Error in `-.default`(tsInfPatDays, t(drop(coredata(tsInfPatDays[1, ])))) :
non-conformable arrays
查看'data.table'包,然後查看'?data.table'中的'roll'和'mult'參數 –