What's the opposite function to lag for an R vector/dataframe?

后端 未结 4 1249
不知归路
不知归路 2021-02-20 11:49

I have a problem dealing with time series in R.

#--------------read data

wb = loadWorkbook(\"Countries_Europe_Prices.xlsx\") 
df = readWorksheet(wb, sheet=\"Sh         


        
4条回答
  •  一个人的身影
    2021-02-20 12:37

    How about the built-in 'lead' function? (from the dplyr package) Doesn't it do exactly the job of Ahmed's function?

    cbind(x, lead(y, 1))
    

    If you want to be able to calculate either positive or negative lags in the same function, i suggest a 'shorter' version of his 'shift' function:

    shift = function(x, lag) {
      require(dplyr)
      switch(sign(lag)/2+1.5, lead(x, abs(lag)), lag(x, abs(lag)))
    }
    

    What it does is creating 2 cases, one with lag the other with lead, and chooses one case depending on the sign of your lag (the +1.5 is a trick to transform a {-1, +1} into a {1, 2} alternative).

提交回复
热议问题