Maximum rolling sum in data frame

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



Maximum rolling sum in data frame



I want to obtain the largest possible sum for a time period.



For example, I have a data frame with units in store for a certain product:


library(tidyverse)

data <- tibble(
date = paste("Day", 1:5),
units_in_store = c(10,3,-2,1,-1)
)



cumsum(data$units_in_store) would return 11 but the largest possible sum in that case is 13, and summing one by one the values would be 13, 11, 12 and 11.


cumsum(data$units_in_store)



Is there a way to compute the maximum moving/rolling sum?



In other words: How can I compute the largest possible sum with



Day 1 + Day2



Day 1 + Day 2 + Day 3



Day 1 + Day 2 + Day 3 + Day 4



etc?



This would be the expected output:


data %>% mutate(units2 = something(units_in_store))

# A tibble: 5 x 3
date units_in_store units2
<chr> <dbl> <dbl>
1 Day 1 10 13
2 Day 2 3 13
3 Day 3 -2 13
4 Day 4 1 13
5 Day 5 -1 13





Could you show your expected output?
– Lamia
Aug 9 at 19:48





sure! I did that
– pachamaltese
Aug 9 at 19:51




2 Answers
2



You mean something like this?


data<-mutate(data,units2=max(cumsum(units_in_store)))



output:


date units_in_store units2
<chr> <dbl> <dbl>
1 Day 1 10 13
2 Day 2 3 13
3 Day 3 -2 13
4 Day 4 1 13
5 Day 5 -1 13



We can use Reduce to get the result "summing one by one":


Reduce


> Reduce("+",data$units_in_store, accumulate = TRUE)[-1]
[1] 13 11 12 11



This is an alternative to cumsum see @doviod´s answer. Then you can select the max value.


cumsum






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

make 2 or more post in bootsrap

Store custom data using WC_Cart add_to_cart() method in Woocommerce 3

Firebase Auth - with Email and Password - Check user already registered