I have a dataset and want to create a column called stock. In particular, the rule is the following.
- If an agent won the game in the previous month, they have a
stockbased on the quantity in the previous month. - This
stockvanishes after three months (e.g., if an agent won on2020-02-01, this stock disappears when they participate in a game on2020-06-01. - There are many agents
A,B, etc.
How do I create such a column using tibble?
Case 1: Simple version
date = c("2020-01-01", "2020-02-01", "2020-03-01","2020-04-01", "2020-05-01", "2020-06-01", "2020-07-01", "2020-08-01", "2020-01-01", "2020-02-01", "2020-03-01", "2020-04-01", "2020-05-01", "2020-08-01")
id = c("A", "A", "A", "A", "A", "A", "A", "A", "B", "B", "B", "B", "B", "B")
win = c(0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0)
quantity = c(60, 50, 50, 100, 10, 10, 100, 100, 60, 50, 50, 10, 10, 100)
dat <- tibble(date = as.Date(date), id = id, win = win, quantity = quantity)
date id win quantity stock
<date> <chr> <dbl> <dbl> <dbl>
2020-01-01 A 0 60 0
2020-02-01 A 1 50 0
2020-03-01 A 0 50 50 ## have 50 for 3 months because A win in the previous month
2020-04-01 A 1 100 50
2020-05-01 A 0 10 150 ## have 100 for 3 months because A win in the previous month
2020-06-01 A 0 10 100 ## disappear 50 after 3 months
2020-07-01 A 0 100 100 ## disappear 50 after 3 months
2020-08-01 A 0 100 0 ## disappear 100 after 3 months
2020-01-01 B 0 60 0
2020-02-01 B 0 50 0
2020-03-01 B 0 50 0
2020-04-01 B 1 10 0
2020-05-01 B 0 10 10
2020-08-01 B 0 100 0
Case2: Real data
gameid = c("A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9", "B1", "B2", "B3", "B4", "B5", "B6")
date = c("2020-01-01", "2020-02-01", "2020-03-01","2020-04-01", "2020-05-01", "2020-06-01", "2020-06-01", "2020-07-01", "2020-08-01", "2020-01-01", "2020-02-01", "2020-03-01", "2020-04-01", "2020-05-01", "2020-08-01")
id = c("A", "A", "A", "A", "A", "A", "A", "A","A", "B", "B", "B", "B", "B", "B")
win = c(0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0)
quantity = c(60, 50, 50, 100, 10, NA, NA, 100, 100, 60, 50, 50, 10, 10, 100)
dat = tibble(gameid = gameid, date = as.Date(date), id = id, win = win, quantity = quantity)
> dat
# A tibble: 15 × 5
gameid date id win quantity
<chr> <date> <chr> <dbl> <dbl>
1 A1 2020-01-01 A 0 60
2 A2 2020-02-01 A 1 50
3 A3 2020-03-01 A 0 50
4 A4 2020-04-01 A 1 100
5 A5 2020-05-01 A 0 10
6 A6 2020-06-01 A 0 NA
7 A7 2020-06-01 A 0 NA # The Case 1 cannot distinguish this part.
8 A8 2020-07-01 A 1 100
9 A9 2020-08-01 A 0 100
10 B1 2020-01-01 B 0 60
11 B2 2020-02-01 B 0 50
12 B3 2020-03-01 B 0 50
13 B4 2020-04-01 B 1 10
14 B5 2020-05-01 B 0 10
15 B6 2020-08-01 B 0 100