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

后端 未结 6 2115
小蘑菇
小蘑菇 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 17:02

    You're going to have a hard time finding an 'elegant' pure-dplyr solution, because dplyr isn't really designed to do this. What dplyr likes to do is map/reduce type operations (mutate and summarize) that use window and summary functions respectively. What you're asking for isn't really either of those, because you want each group to depend on the last, so you're really describing a looping operation with side effects - two very non-R-philosophy operations.

    If you want to hack your way into doing what you describe, you can try an approach like this:

    new.initial.capital <- 0
    for (z in split(df, df$x.long)) {
        z$initial.capital[[1]] <- new.initial.capital
        # some other calculations here
        # maybe you want to modify df as well
        new.initial.capital <- foo
    }
    

    However, this is really not a very R-friendly piece of code, as it depends on side effects and loops. I would advise seeing if you can reframe your calculations in terms of a summary and/or window function if you want to integrate with dplyr.

    For more:
    https://www.rstudio.com/wp-content/uploads/2015/02/data-wrangling-cheatsheet.pdf
    https://danieljhocking.wordpress.com/2014/12/03/lags-and-moving-means-in-dplyr/

提交回复
热议问题