我试图将数据框中的特定列下移(滞后)n 行(例如2 行)。我只找到了有关特定列滞后 1 行的帖子。这是一些模拟数据。
df <- data.frame(
A = seq(1,7),
B = seq(8,14),
C = seq(15,21),
D = seq(22,28)
)
df
> df
A B C D
1 8 15 22
2 9 16 23
3 10 17 24
4 11 18 25
5 12 19 26
6 13 20 27
7 14 21 28
我想要在这里做的是将 A、C 和 D 列中的值下移 n 行,并向我的数据帧添加新行以创建不同的数据帧。具有 2 行滞后的所需输出示例如下所示。
> df.lag.example
A B C D
NA 8 NA NA
NA 9 NA NA
1 10 15 22
2 11 16 23
3 12 17 24
4 13 18 25
5 14 19 26
6 NA 20 27
7 NA 21 28
这是一些快速而肮脏的东西:
foo <- function(df, n, lag_cols) {
result <- df[c(rep(NA, n), 1L:(nrow(df))), ]
non_lag_cols <- setdiff(names(df), lag_cols)
result[non_lag_cols] <- lapply(
result[(n+1):(nrow(result)), non_lag_cols, drop=FALSE],
\(x) c(x, rep(NA, n))
)
return(result)
}
foo(df, 2, c("A", "C", "D"))
# A B C D
# NA NA 8 NA NA
# NA.1 NA 9 NA NA
# 1 1 10 15 22
# 2 2 11 16 23
# 3 3 12 17 24
# 4 4 13 18 25
# 5 5 14 19 26
# 6 6 NA 20 27
# 7 7 NA 21 28
library(dplyr)
rbind(df, df[0,][rep(NA, 2),]) %>%
mutate(across(-2, ~lag(., 2))) %>%
`rownames<-`(NULL)
#> A B C D
#> 1 NA 8 NA NA
#> 2 NA 9 NA NA
#> 3 1 10 15 22
#> 4 2 11 16 23
#> 5 3 12 17 24
#> 6 4 13 18 25
#> 7 5 14 19 26
#> 8 6 NA 20 27
#> 9 7 NA 21 28
创建于 2024-04-18,使用 reprex v2.0.2