在时间序列中经常会用到一个序列的滞后序列,R中的包fMultivar中的函数tslag()提供了这个功能。
其中:x为一个向量,k指定滞后阶数,可以是一个自然数列,若trim为假,则返回序列与原序列长度相同,但含有NA值;若trim项为真,则返回序列中不含有NA值,例如 :
x也可以是一个矩阵, 自动向量化.
[参考]
> install.packages("fMultivar")
> library(fMultivar)
Loading required package: sn
Loading required package: mnormt
Package ‘sn’, 0.4-16 (2010-08-30). Type ‘help(SN)’ for summary information
Loading required package: timeDate
Loading required package: timeSeries
Loading required package: fBasics
Loading required package: MASS
Attaching package: ‘fBasics’
The following object(s) are masked from ‘package:base’:
norm
> args(tslag)
function (x, k = 1, trim = FALSE)
NULL
其中:x为一个向量,k指定滞后阶数,可以是一个自然数列,若trim为假,则返回序列与原序列长度相同,但含有NA值;若trim项为真,则返回序列中不含有NA值,例如 :
> x <- 1:10
> x
[1] 1 2 3 4 5 6 7 8 9 10
> tslag(x, c(1,2,6))
[,1] [,2] [,3]
[1,] NA NA NA
[2,] 1 NA NA
[3,] 2 1 NA
[4,] 3 2 NA
[5,] 4 3 NA
[6,] 5 4 NA
[7,] 6 5 1
[8,] 7 6 2
[9,] 8 7 3
[10,] 9 8 4
> tslag(x, c(1,2,6), TRUE)
[,1] [,2] [,3]
[1,] 6 5 1
[2,] 7 6 2
[3,] 8 7 3
[4,] 9 8 4
x也可以是一个矩阵, 自动向量化.
> x <- matrix(1:12,3,4)
> x
[,1] [,2] [,3] [,4]
[1,] 1 4 7 10
[2,] 2 5 8 11
[3,] 3 6 9 12
> tslag(x, c(1,2,6), FALSE)
[,1] [,2] [,3]
[1,] NA NA NA
[2,] 1 NA NA
[3,] 2 1 NA
[4,] 3 2 NA
[5,] 4 3 NA
[6,] 5 4 NA
[7,] 6 5 1
[8,] 7 6 2
[9,] 8 7 3
[10,] 9 8 4
[11,] 10 9 5
[12,] 11 10 6
> tslag(x, c(1,2,6), TRUE)
[,1] [,2] [,3]
[1,] 6 5 1
[2,] 7 6 2
[3,] 8 7 3
[4,] 9 8 4
[5,] 10 9 5
[6,] 11 10 6
[参考]
1. > help(tslag)
tslag package:fBasics R Documentation
Lagged or Leading Vector/Matrix
Description:
Creates a lagged or leading vector/matrix of selected order(s).
Usage:
tslag(x, k = 1, trim = FALSE)
Arguments:
k: an integer value, the number of positions the new series is
to lag or to lead the input series.
x: a numeric vector or matrix, missing values are allowed.
trim: a logical flag, if TRUE, the missing values at the beginning
ans/or end of the returned series will be trimmed. The
default value is FALSE.
See Also:
‘pdl’.
Examples:
## tslag -
#