0

I have a data that determines the package of each customer at a point in time.

date    customer    package
1/1/2015    12        2
2/1/2015    12        5
3/1/2015    12        2
4/1/2015    12        3
5/1/2015    12        6
6/1/2015    12        7
7/1/2015    12        5
8/1/2015    12        3
9/1/2015    12        2

I want to group by customer and get the largest package he has reached to before that point in time. The output should be like that:

date    customer    package lagged_max
1/1/2015    12        2        2
2/1/2015    12        5        5
3/1/2015    12        2        5
4/1/2015    12        3        5
5/1/2015    12        6        6
6/1/2015    12        7        7
7/1/2015    12        5        7
8/1/2015    12        3        7 
9/1/2015    12        2        7

data %>% group_by(customer) %>% mutate(max_package = max(package)

Gets the maximum package overall but I want it to ignore only that in the past.

Nareman Darwish
  • 1,251
  • 7
  • 14

1 Answers1

0

Replace the mutate shown in the question with the one below:

library(dplyr)

data %>%
     group_by(customer) %>%
     mutate(cummax = cummax(package)) %>%
     ungroup

giving:

# A tibble: 9 x 4
  date       customer package cummax
  <date>        <int>   <int>  <int>
1 2015-01-01       12       2      2
2 2015-01-02       12       5      5
3 2015-01-03       12       2      5
4 2015-01-04       12       3      5
5 2015-01-05       12       6      6
6 2015-01-06       12       7      7
7 2015-01-07       12       5      7
8 2015-01-08       12       3      7
9 2015-01-09       12       2      7

Note

The input data in reproducible form is:

Lines <- "
date    customer    package
1/1/2015    12        2
2/1/2015    12        5
3/1/2015    12        2
4/1/2015    12        3
5/1/2015    12        6
6/1/2015    12        7
7/1/2015    12        5
8/1/2015    12        3
9/1/2015    12        2"

data <- read.table(text = Lines, header = TRUE)
data$date <- as.Date(data$date, format = "%d/%m/%Y")
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341