滞后/超前R中的整个数据帧 [英] lag/lead entire dataframe in R
问题描述
我很难带领或落后于整个数据帧。我能做的是通过以下尝试移动单个列,但不是全部操作:
I am having a very hard time leading or lagging an entire dataframe. What I am able to do is shifting individual columns with the following attempts but not the whole thing:
require('DataCombine')
df_l <- slide(df, Var = var1, slideBy = -1)
使用colnames(x_ret_mon)作为Var无效,我被告知在数据帧中找不到变量名称。
using colnames(x_ret_mon) as Var does not work, I am told the variable names are not found in the dataframe.
此尝试将列向右移动但不向下移动:
This attempt shifts the columns right but not down:
df_l<- dplyr::lag(df)
这只会为滞后变量创建新变量,但我不知道如何有效删除旧的非滞后值:
This only creates new variables for the lagged variables but then I do not know how to effectively delete the old non lagged values:
df_l<-shift(df, n=1L, fill=NA, type=c("lead"), give.names=FALSE)
推荐答案
使用 dplyr :: mutate_all
进行申请滞后或引向所有列。
Use dplyr::mutate_all
to apply lags or leads to all columns.
df = data.frame(a = 1:10, b = 21:30)
dplyr::mutate_all(df, lag)
a b
1 NA NA
2 1 21
3 2 22
4 3 23
5 4 24
6 5 25
7 6 26
8 7 27
9 8 28
10 9 29
这篇关于滞后/超前R中的整个数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!