本文介绍了R 中的滞后变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 R 中为任意变量(即不是常规时间序列)制作滞后变量矩阵的最有效方法是什么

What is the most efficient way to make a matrix of lagged variables in R for an arbitrary variable (i.e. not a regular time series)

例如:

输入:

x <- c(1,2,3,4) 

2 个滞后,输出:

[1,NA, NA]
[2, 1, NA]
[3, 2,  1]
[4, 3,  2]

推荐答案

您可以使用内置的 embed() 函数来实现这一点,它的第二个维度"参数等同于您的'已经称为'滞后':

You can achieve this using the built-in embed() function, where its second 'dimension' argument is equivalent to what you've called 'lag':

x <- c(NA,NA,1,2,3,4)
embed(x,3)

## returns
     [,1] [,2] [,3]
[1,]    1   NA   NA
[2,]    2    1   NA
[3,]    3    2    1
[4,]    4    3    2

embed()之前的答案 由 Joshua Reich 提供.(请注意,我在 x 前面加上了 NA 来复制您想要的输出).

embed() was discussed in a previous answer by Joshua Reich. (Note that I prepended x with NAs to replicate your desired output).

它不是特别好命名,但对于涉及滑动窗口的操作(例如滚动总和和移动平均线)非常有用和强大.

It's not particularly well-named but it is quite useful and powerful for operations involving sliding windows, such as rolling sums and moving averages.

这篇关于R 中的滞后变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 01:09