dplyr group by, carry forward value from previous group to next

后端 未结 6 2147
小蘑菇
小蘑菇 2020-12-31 16:50

Ok this is the over all view of what i\'m trying to achieve with dplyr:

Using dplyr I am making calculations to form new columns.

initial.         


        
6条回答
  •  长情又很酷
    2020-12-31 16:57

    It took me a very long time to understand what you are going for: for a single "update", does this work?

    library(tidyverse)
    library(magrittr)
    temp <- df %>% 
      dplyr::mutate(RunID = data.table::rleid(x.long)) %>%
      group_by(RunID) %>% # Don't delete the RunID 
      dplyr::mutate(max.new = max(new.initial.capital)) %>% 
      slice(1) %>%
      arrange(x.long) %>% 
      dplyr::mutate(pass.value = lag(max.new))
    
    df <- left_join(df, temp %>% dplyr::select(x.long, RunID, pass.value)
    

    After this, replace values of initial.capital using pass.value column, according to grouped row_number as you have done above.

    I'm not quite sure how to go about it without looping this updating procedure, and I guess if you want to do 10,000 updates like this it will certainly be a bummer. But it will be enable you to "pass" the value to the second red cell as in your picture.

提交回复
热议问题