R中的滞后变量 [英] Lagging Variables in R

查看:34
本文介绍了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() 函数来实现这一点,它的第二个 'dimension' 参数等同于您的'已经称为'滞后':

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中的滞后变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆