我想创建多个变量的多个滞后,所以我认为编写一个函数会有所帮助。我的代码抛出警告(“Truncating vector to length 1”)和错误结果:
library(dplyr)
time <- c(2000:2009, 2000:2009)
x <- c(1:10, 10:19)
id <- c(1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2)
df <- data.frame(id, time, x)
three_lags <- function (data, column, group, ordervar) {
data <- data %>%
group_by_(group) %>%
mutate(a = lag(column, 1L, NA, order_by = ordervar),
b = lag(column, 2L, NA, order_by = ordervar),
c = lag(column, 3L, NA, order_by = ordervar))
}
df_lags <- three_lags(data=df, column=x, group=id, ordervar=time) %>%
arrange(id, time)
我也想知道是否有更优雅的解决方案使用
mutate_each
,但我也没有让它起作用。我当然可以为每个新的滞后变量编写一个包含一行的长代码,但我想避免这种情况。编辑:
akrun 的 dplyr 答案有效,但需要很长时间来计算大型数据帧。使用
data.table
的解决方案似乎更有效率。因此,仍然可以找到一个 dplyr 或其他解决方案,它也允许为几列和几个滞后实现。编辑2:
对于多列且没有组(例如“ID”),以下解决方案似乎非常适合我,因为它很简单。代码当然可以缩短,但要一步一步:
df <- arrange(df, time)
df.lag <- shift(df[,1:24], n=1:3, give.names = T) ##column indexes of columns to be lagged as "[,startcol:endcol]", "n=1:3" sepcifies the number of lags (lag1, lag2 and lag3 in this case)
df.result <- bind_cols(df, df.lag)
最佳答案
我们可以使用 shift
来自 data.table
可以为“n”取多个值
library(data.table)
setDT(df)[order(time), c("a", "b", "c") := shift(x, 1:3) , id][order(id, time)]
假设,我们需要在多个列上执行此操作
df$y <- df$x
setDT(df)[order(time), paste0(rep(c("x", "y"), each =3),
c("a", "b", "c")) :=shift(.SD, 1:3), id, .SDcols = x:y]
shift
也可用于dplyr
library(dplyr)
df %>%
group_by(id) %>%
arrange(id, time) %>%
do(data.frame(., setNames(shift(.$x, 1:3), c("a", "b", "c"))))
# id time x a b c
# <dbl> <int> <int> <int> <int> <int>
#1 1 2000 1 NA NA NA
#2 1 2001 2 1 NA NA
#3 1 2002 3 2 1 NA
#4 1 2003 4 3 2 1
#5 1 2004 5 4 3 2
#6 1 2005 6 5 4 3
#7 1 2006 7 6 5 4
#8 1 2007 8 7 6 5
#9 1 2008 9 8 7 6
#10 1 2009 10 9 8 7
#11 2 2000 10 NA NA NA
#12 2 2001 11 10 NA NA
#13 2 2002 12 11 10 NA
#14 2 2003 13 12 11 10
#15 2 2004 14 13 12 11
#16 2 2005 15 14 13 12
#17 2 2006 16 15 14 13
#18 2 2007 17 16 15 14
#19 2 2008 18 17 16 15
#20 2 2009 19 18 17 16
关于r - 调试 : function to create multiple lags for multiple columns (dplyr),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38119225/