如果条件匹配,我想用 NA 填充所有滞后行。 我在我的示例数据框中解释它:
> df
# A tibble: 10 x 3
date condition return
<date> <dbl> <int>
1 2020-05-28 0 1
2 2020-05-29 0 2
3 2020-05-30 1 3
4 2020-05-31 0 4
5 2020-06-01 0 5
6 2020-06-02 0 6
7 2020-06-03 0 7
8 2020-06-04 0 8
9 2020-06-05 0 9
10 2020-06-06 0 10
现在我正在尝试基于“return”列改变多个(在本例中为 3 个)新列,如下所示:
如果滞后“condition”值 == 1,则将“return”值替换为 NA
。
这同样适用于其他滞后 (1,2,3)。但在这种情况下,必须为所有滞后填充 NA:
date condition return lag1 lag2 lag3
<date> <dbl> <int> <int> <int> <int>
1 2020-05-28 0 1 1 1 1
2 2020-05-29 0 2 2 2 2
3 2020-05-30 1 3 3 3 3
4 2020-05-31 0 4 NA NA NA
5 2020-06-01 0 5 5 NA NA
6 2020-06-02 0 6 6 6 NA
7 2020-06-03 0 7 7 7 7
8 2020-06-04 0 8 8 8 8
9 2020-06-05 0 9 9 9 9
10 2020-06-06 0 10 10 10 10
有人可以帮助我吗?
这是我的数据框:
df <- tibble(date = lubridate::today() + lubridate::days(1:10),
condition = c(0,0,1,0,0,0,0,0,0,0),
return = 1:10)
最佳答案
您可以使用"[<-"()
分配NA
进入条件匹配的位置。
library(dplyr)
df %>%
mutate(lag1 = `[<-`(return, which(condition == 1) + 1, NA),
lag2 = `[<-`(return, which(condition == 1) + 1:2, NA),
lag3 = `[<-`(return, which(condition == 1) + 1:3, NA))
如果您不想为每个滞后编写一行,则可以将所需的任何滞后设置为矢量对象并应用 mutate()
迭代reduce()
在purrr
.
library(purrr)
lag_num <- 1:3
reduce(lag_num,
~ mutate(.x, !!paste0("lag", .y) := `[<-`(return, which(condition == 1) + 1:.y, NA)),
.init = df)
对应base
R版本:
Reduce(function(x, y){
x[[paste0("lag", y)]] <- `[<-`(x$return, which(x$condition == 1) + 1:y, NA)
return(x)
}, lag_num, init = df)
输出
# # A tibble: 10 x 6
# date condition return lag1 lag2 lag3
# <date> <dbl> <int> <int> <int> <int>
# 1 2020-05-28 0 1 1 1 1
# 2 2020-05-29 0 2 2 2 2
# 3 2020-05-30 1 3 3 3 3
# 4 2020-05-31 0 4 NA NA NA
# 5 2020-06-01 0 5 5 NA NA
# 6 2020-06-02 0 6 6 6 NA
# 7 2020-06-03 0 7 7 7 7
# 8 2020-06-04 0 8 8 8 8
# 9 2020-06-05 0 9 9 9 9
# 10 2020-06-06 0 10 10 10 10
关于R 如果滞后条件匹配,则用 NA 填充新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62046158/