Creating Lagged Differences in R Time Series
Summary
The question asks how to calculate successive differences at several lags in R, rather than percentage returns. It starts from an S&P 500 price series and notes that the finance-oriented Delt function returns percentage changes. The answer recommends using a lag function, or a custom shift operation for numeric vectors that does not rely on time-series object structure. The shift method places missing values at the ends where observations are unavailable and can be applied to multiple shift amounts.
This is a programming-oriented exchange with no market analysis, empirical results, or comparison of implementations. It offers a practical distinction between percentage change and absolute lagged differences, but does not provide the final differencing calculation or discuss handling missing values, time alignment, or time-series classes in depth. Its value is mainly as a small data preparation idea for return and price-series workflows.
Key ideas
- Delt calculates percentage changes, while the question seeks absolute differences between observations separated by a lag.
- A lag or shift operation can align current and earlier values for later subtraction.
- A numeric-vector shift can operate independently of a time-series object's structure.
- Unavailable values at the shifted boundaries are represented as missing observations.
Tags
Full text
# How to create time series with lagged in R
# How to create time series with lagged in R
Would anyone else advise me, how to create time series with lagged in R. I would the result is the difference with lagged, there is a function Delt() but the result is the percentage change. Please advise how to do that. Thank you
```
getSymbols("^GSPC")
DeltLagGSPC<-Delt(Cl(GSPC),k=1:5)
```
update
I would calculate the computed result with the successive difference. The output format of Delt() is same as I expected, but the result is the percentage change with lagged. I would calculate the difference with lagged. Is there any function, same parameters as Delt() but calculate the difference change.
## Answer by Richi Wa (score 1)
https://quant.stackexchange.com/a/25328
Look at the function "lag" and if you want a lag function that does not depend on some time series structure of the object then you can use this one:
```
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
}
```
I prefer it in the meanwhile. It was taken from here.Shown in full with attribution under the source's licence. Licence: CC BY-SA 4.0 (Stack Exchange)
This summary was written by Stratmill's research agent from the original; it is not a copy of the source.