Which opposite function is behind the R-vector / data frame?

I have a time series problem in R.

#--------------read data wb = loadWorkbook("Countries_Europe_Prices.xlsx") df = readWorksheet(wb, sheet="Sheet2") x <- df$Year y <- df$Index1 y <- lag(y, 1, na.pad = TRUE) cbind(x, y) 

It gives me the following result:

  xy [1,] 1974 NA [2,] 1975 50.8 [3,] 1976 51.9 [4,] 1977 54.8 [5,] 1978 58.8 [6,] 1979 64.0 [7,] 1980 68.8 [8,] 1981 73.6 [9,] 1982 74.3 [10,] 1983 74.5 [11,] 1984 72.9 [12,] 1985 72.1 [13,] 1986 72.3 [14,] 1987 71.7 [15,] 1988 72.9 [16,] 1989 75.3 [17,] 1990 81.2 [18,] 1991 84.3 [19,] 1992 87.2 [20,] 1993 90.1 

But I want the first value in y to be 50.8 and so on. In other words, I want to get a negative lag. I don’t understand how can I do this?

My problem is very similar to this problem, but I cannot solve it. I think I still do not understand the solution (s) ...

Base lag in vector / frame R

+8
source share
4 answers

What about the built-in lead function? (from dplyr package) Does this not fulfill the function of Ahmed?

 cbind(x, lead(y, 1)) 

If you want to calculate positive or negative lags in the same function, I suggest a "shorter" version of its shift function:

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

He creates 2 cases, one with a backlog, the other with lead, and selects one case depending on the sign of your backlog (+1.5 is a trick for converting {-1, +1.]} To the {1, 2} alternative).

+9
source

There is an easier way to do this, which I completely captured from this link . What I will do here explains what you should do in stages:

First create the following function by executing the following code:

 shift<-function(x,shift_by){ stopifnot(is.numeric(shift_by)) stopifnot(is.numeric(x)) if (length(shift_by)>1) return(sapply(shift_by,shift, x=x)) out<-NULL abs_shift_by=abs(shift_by) if (shift_by > 0 ) out<-c(tail(x,-abs_shift_by),rep(NA,abs_shift_by)) else if (shift_by < 0 ) out<-c(rep(NA,abs_shift_by), head(x,-abs_shift_by)) else out<-x out } 

This will create a function called shift with two arguments; one of them is the vector that you need to control its lag / wire, and the other is the number of lags / wires that you need.

Example:

Suppose you have the following vector:

 x<-seq(1:10) x [1] 1 2 3 4 5 6 7 8 9 10 

if you need x first order lag

 shift(x,-1) [1] NA 1 2 3 4 5 6 7 8 9 

if you need x first order output (negative lag)

 shift(x,1) [1] 2 3 4 5 6 7 8 9 10 NA 
+3
source

A simpler solution:

 y = dplyr::lead(y,1) 
0
source

The opposite of lag () is lead ()

0
source

Source: https://habr.com/ru/post/1213056/


All Articles