'R function to show the items held in previous periods

I am currently working with a project, the details are:

  1. I have the item ID and item quantity the team has for each period, here is a simple example enter image description here

  2. The quantity and item held by each team will be changing over time. But from period 2, I also want to show the item had been held for each team in the previous 2 periods, then the quantity will be 0.

enter image description here

I have over 5000 teams and over 50000 items, so it is impossible to separate them into different dataframe. Is there any way to do it? with a loop?

Many thanks for your help

And please see the sample data used.

structure(list(Item_ID = c(123, 124, 125, 121, 122, 121, 122, 
123, 123, 124, 126, 121, 122, 121, 122, 127, 128, 129, 124, 126, 
124, 129, 128, 122), Item_Quantity = c(100, 200, 300, 200, 300, 
200, 300, 100, 100, 200, 100, 200, 300, 200, 300, 200, 400, 500, 
100, 200, 100, 100, 100, 100), Period = c(1, 1, 1, 1, 1, 1, 1, 
1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3), Team = c("A", 
"A", "A", "B", "B", "C", "C", "C", "A", "A", "B", "B", "B", "C", 
"C", "A", "A", "A", "B", "B", "C", "C", "C", "C")), class = c("tbl_df", 
"tbl", "data.frame"), row.names = c(NA, -24L))
r


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source