我有一个数据帧,如下所示:
ID | 计数 |
---|---|
1 | |
2 | 5 |
3 | |
4 | |
5 | 1 |
# set as data.table
setDT(df)
# shift
df[, count := shift(count, 1)]
df$Count=c(NA, df$Count[1:(nrow(df)-1)])
1(dplyr使用注释末尾可重复显示的DF
,使用dplyr 的滞后和领先
library(dplyr)
DF %>% mutate(CountLag = lag(Count), CountLead = lead(Count))
## ID Count CountLag CountLead
## 1 1 3 NA 5
## 2 2 5 3 2
## 3 3 2 5 0
## 4 4 0 2 1
## 5 5 1 0 NA
2(zoo这将使用zoo的矢量化滞后创建zoo对象。(可选(使用强化.zoo(z(或as.ts(z(将其转换回数据帧或ts对象。
请注意,dplyr的clobbers有自己的滞后,所以我们使用了stats:lag来确保它不会干扰。如果没有加载dplyr,则可以选择省略stats::。
library(zoo)
z <- stats::lag(read.zoo(DF), seq(-1, 1)); z
Index lag-1 lag0 lag1
1 1 NA 3 5
2 2 3 5 2
3 3 5 2 0
4 4 2 0 1
5 5 0 1 NA
3(collapse来自collapse包的标志也在其第二个参数上向量化。
library(collapse)
with(DF, data.frame(ID, Count = flag(Count, seq(-1, 1))))
## ID Count.F1 Count... Count.L1
## 1 1 5 3 NA
## 2 2 2 5 3
## 3 3 0 2 5
## 4 4 1 0 2
## 5 5 NA 1 0
备注
DF <- data.frame(ID = 1:5, Count = c(3, 5, 2, 0, 1))