R向量/数据帧中的基本滞后 [英] Basic lag in R vector/dataframe
本文介绍了R向量/数据帧中的基本滞后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
很可能会暴露我是 R 新手,但在 SPSS 中,运行滞后非常容易.显然这是用户错误,但我错过了什么?
Will most likely expose that I am new to R, but in SPSS, running lags is very easy. Obviously this is user error, but what I am missing?
x <- sample(c(1:9), 10, replace = T)
y <- lag(x, 1)
ds <- cbind(x, y)
ds
结果:
x y
[1,] 4 4
[2,] 6 6
[3,] 3 3
[4,] 4 4
[5,] 3 3
[6,] 5 5
[7,] 8 8
[8,] 9 9
[9,] 3 3
[10,] 7 7
我想我会看到:
x y
[1,] 4
[2,] 6 4
[3,] 3 6
[4,] 4 3
[5,] 3 4
[6,] 5 3
[7,] 8 5
[8,] 9 8
[9,] 3 9
[10,] 7 3
任何指导将不胜感激.
推荐答案
解决这个问题的另一种方法是使用 zoo 包,它有一个 lag 方法,可以用 NA 填充结果:
Another way to deal with this is using the zoo package, which has a lag method that will pad the result with NA:
require(zoo)
> set.seed(123)
> x <- zoo(sample(c(1:9), 10, replace = T))
> y <- lag(x, -1, na.pad = TRUE)
> cbind(x, y)
x y
1 3 NA
2 8 3
3 4 8
4 8 4
5 9 8
6 1 9
7 5 1
8 9 5
9 5 9
10 5 5
结果是一个多元动物园对象(它是一个增强矩阵),但很容易通过
The result is a multivariate zoo object (which is an enhanced matrix), but easily converted to a data.frame via
> data.frame(cbind(x, y))
这篇关于R向量/数据帧中的基本滞后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文