R 检查是否需要添加新期间,并在需要时添加

R 检查是否需要添加新期间,并在需要时添加,r,time-series,R,Time Series,我用时间序列为瑞典的同质化者解答问题。我现在正在使用Eviews来更新这个系列,但是我希望能够在R中做到这一点 在这个简化的例子中,我有3个问题,我们在过去的不同日期问过 temp <- c(1:98) q1 <- ts(temp,start=c(2009,1),frequency = 12) temp <- c(1:122) q2 <- ts(temp,start=c(2007,1),frequency = 12) temp <- c(1:136) q3 <

我用时间序列为瑞典的同质化者解答问题。我现在正在使用Eviews来更新这个系列,但是我希望能够在R中做到这一点

在这个简化的例子中,我有3个问题,我们在过去的不同日期问过

temp <- c(1:98)
q1 <- ts(temp,start=c(2009,1),frequency = 12)
temp <- c(1:122)
q2 <- ts(temp,start=c(2007,1),frequency = 12)
temp <- c(1:136)
q3 <- ts(temp,start=c(2005,11),frequency = 12)
print(q1)


     Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
2009   1   2   3   4   5   6   7   8   9  10  11  12
2010  13  14  15  16  17  18  19  20  21  22  23  24
2011  25  26  27  28  29  30  31  32  33  34  35  36
2012  37  38  39  40  41  42  43  44  45  46  47  48
2013  49  50  51  52  53  54  55  56  57  58  59  60
2014  61  62  63  64  65  66  67  68  69  70  71  72
2015  73  74  75  76  77  78  79  80  81  82  83  84
2016  85  86  87  88  89  90  91  92  93  94  95  96
2017  97  98 

temp以下是解决此问题的函数:

tsenter <- function(series,year,month,value)
{
  startper <- start(series)
  endper <- end(series)

  if(startper[1]==year)
  {
    periods <-month - startper[2]+1
  }
  else if(startper[1]+1==year)
  {
    periods <- 12-startper[2]+1+month
  }
  else
  {
    periods <- 12-startper[2]+1+month+(year-startper[1]-1)*12
  }
  if(periods>0)
  {
    if(endper[1]<year || (endper[1]==year && endper[2]<month))
    {
      series <- window(series, start(series), c(year, month), extend=TRUE)
    }
    print(periods)
    print(value)
    series <- replace (series,periods,value)
  }else{
    print("period före startperiod")
  }  
}

tsenter
window
似乎成功地扩展了时间序列:
q1虽然我可以这样做,然后把q1放在自动化程度稍高的地方,但是可以使用
start
end
函数:
q1 start(q1)对于这部分来说是一个很好的函数。但是否有办法检查某个月的“订单号”(2017年3月的订单号为99)。有时我们必须在前一个月重新运行。通常,您可以使用
head
tail
从向量中提取值。例如,
tail(q1,1)
将给出q1的最终值,
head(q1,5)
将给出前5个值。
year <- 2015
month <- 3


temp <- c(1:98)
q1 <- ts(temp,start=c(2009,1),frequency = 12)
temp <- c(1:122)
q2 <- ts(temp,start=c(2007,1),frequency = 12)
temp <- c(1:136)
q3 <- ts(temp,start=c(2005,11),frequency = 12)
q1 <- tsenter (series = q1,year = year,month = month,value = 100)
q2 <- tsenter (series = q2,year = year,month = month,value = 99)
q3 <- tsenter (series = q3,year = year,month = month,value = 27)


print(q1)
print(q2)
print(q3)