gpt4 book ai didi

R 如果匹配滞后条件,则用 NA 填充新列

转载 作者:行者123 更新时间:2023-12-04 09:48:52 25 4
gpt4 key购买 nike

如果条件匹配,我想用 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

现在我正在尝试改 rebase 于“返回”列的多个(在本例中为 3)新列,如下所示:

如果滞后“条件”值 == 1,则将“返回”值替换为 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com