如何创建滞后变量 [英] How to create lag variables
本文介绍了如何创建滞后变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想为变量pm10创建滞后变量,并使用以下代码.但是,我无法获得想要的东西.我该如何创建pm10的滞后时间?
I want to create lagged variable for a variable pm10 and used the following code. However, I could not get what I wanted. How could I create a lag of pm10?
df2$l1pm10 <- lag(df2$pm10, -1, na.pad = TRUE)
df2$l1pm102 <- lag(df2$pm10, 1)
dput(df2)
structure(list(var1 = 1:10, pm10 = c(26.956073733, NA, 32.838694951,
39.9560737332, NA, 40.9560737332, 33.956073733, 28.956073733,
32.348770798, NA), l1pm10 = structure(c(26.956073733, NA, 32.838694951,
39.9560737332, NA, 40.9560737332, 33.956073733, 28.956073733,
32.348770798, NA), .Tsp = c(2, 11, 1))), .Names = c("var1", "pm10",
"l1pm10"), row.names = c("1", "2", "3", "4", "5", "6", "7", "8",
"9", "10"), class = "data.frame")
推荐答案
在基数R中,函数lag()
对于时间序列对象很有用.这里有一个数据框,情况有些不同.
In base R the function lag()
is useful for time series objects. Here you have a dataframe and the situation is somewhat different.
您可以尝试以下方法,我承认这不是很优雅:
You could try the following, which I admit is not very elegant:
df2$l1pm10 <- sapply(1:nrow(df2), function(x) df2$pm10[x+1])
df2$l1pm102 <- sapply(1:nrow(df2), function(x) df2$pm10[x-1])
#> df2
# var1 pm10 l1pm10 l1pm102
#1 1 26.95607 NA
#2 2 NA 32.83869 26.95607
#3 3 32.83869 39.95607 NA
#4 4 39.95607 NA 32.83869
#5 5 NA 40.95607 39.95607
#6 6 40.95607 33.95607 NA
#7 7 33.95607 28.95607 40.95607
#8 8 28.95607 32.34877 33.95607
#9 9 32.34877 NA 28.95607
#10 10 NA NA 32.34877
另一种方法是使用Hmisc
软件包中的Lag()
函数(用大写字母"L"表示):
An alternative consists in using the Lag()
function (with capital "L") from the Hmisc
package:
library(Hmisc)
df2$l1pm10 <- Lag(df2$pm10, -1)
df2$l1pm102 <- Lag(df2$pm10, +1)
#> df2
# var1 pm10 l1pm10 l1pm102
#1 1 26.95607 NA NA
#2 2 NA 32.83869 26.95607
#3 3 32.83869 39.95607 NA
#4 4 39.95607 NA 32.83869
#5 5 NA 40.95607 39.95607
#6 6 40.95607 33.95607 NA
#7 7 33.95607 28.95607 40.95607
#8 8 28.95607 32.34877 33.95607
#9 9 32.34877 NA 28.95607
#10 10 NA NA 32.34877
这篇关于如何创建滞后变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文