如何基于其他列生成列的运行总计

时间:2019-04-26 03:07:36

标签: r tidyverse

我有一个df,其中有两列bear_start_counttd_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_countbear_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既提供了现有列,也提供了计算出的列。

关于如何解决此问题的任何想法

1 个答案:

答案 0 :(得分:2)

一种选择是根据'bear_start_count','td_sell_setup'列使用rleid创建分组变量,然后检查if的{​​{1}} d值“ 10”,“ 01”在组中,然后让pasterow_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)