我有一个df,其中有两列bear_start_count
和td_sell_setup
。
使用这两列,我需要锻炼另一列td_sell_count
。
td_sell_count
的条件如下:
当bear_start_count
== 1和td_sell_setup
== 0时,则td_sell_count
== 1
此后,当bear_start_count
== 0和td_sell_setup
== 1时; td_sell_count
=前一行td_sell_count
+当前行td_sell_setup
的值
当td_sell_count
和bear_start_count
== 0时,td_sell_setup
重置为0
library(tidyverse)
df <- data.frame(
bear_start_count = c(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0),
td_sell_setup = c(1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0,
0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1),
td_sell_count = c(0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 0, 0,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20)
)
上面的df既提供了现有列,也提供了计算出的列。
关于如何解决此问题的任何想法
答案 0 :(得分:2)
一种选择是根据'bear_start_count','td_sell_setup'列使用rleid
创建分组变量,然后检查if
的{{1}} d值“ 10”,“ 01”在组中,然后让paste
或row_number()
返回0(用else
实现)
case_when
-检查OP的预期输出
library(data.table)
library(dplyr)
library(stringr)
out <- df %>%
mutate(newcol = str_c(bear_start_count, td_sell_setup)) %>%
group_by(grp = rleid(newcol %in% c("10", "01"))) %>%
mutate(td_sell_count1 = case_when(all(c("10", "01") %in% newcol)
~ row_number(), TRUE ~ 0L)) %>%
ungroup %>%
select(-grp, -newcol)