I have a dataframe like the one below
ItemNo OrderAmount Date
3845 320 2020-01-21
3245 -100 2020-01-20
4045 -200 2020-01-20
3845 300 2020-01-19
3845 320 2020-01-18
3245 100 2020-01-18
3645 230 2020-01-18
3645 -230 2020-01-18
3245 -100 2020-01-18
3845 320 2020-01-17
4045 0 2020-01-17
3845 320 2020-01-17
3845 -300 2020-01-17
3245 200 2020-01-17
3645 230 2020-01-16
4045 200 2020-01-15
3845 -300 2020-01-15
3245 100 2020-01-15
3245 100 2020-01-15
3845 320 2020-01-15
4045 240 2020-01-15
4045 0 2020-01-15
I wish to match negative and positive numbers within a group (ItemNo), and then delete the matched rows from the data frame. If the OrderAmount is 0, then it is kept in the dataframe. I want the output to be
ItemNo OrderAmount Date
3845 320 2020-01-21
3845 320 2020-01-18
3245 100 2020-01-18
3645 230 2020-01-18
3845 320 2020-01-17
4045 0 2020-01-17
3845 320 2020-01-17
3845 -300 2020-01-17
3245 200 2020-01-17
3845 320 2020-01-15
4045 240 2020-01-15
4045 0 2020-01-15
I have tried using:
# Dataframe
DF <- data.frame(ItemNo=c(3845,3245,4045,3845,3845,3245,3645,3645,3245,3845,4045,3845,3845,3245,3645,4045,3845,3245,3245,3845,4045,4045),
OrderAmount = c(320,-100,-200,300,320,100,230,-230,-100,320,0,320,-300,200,230,200,-300,100,100,320,240,0),
Date = c("2020-01-21","2020-01-20","2020-01-20","2020-01-19","2020-01-18","2020-01-18","2020-01-18","2020-01-18","2020-01-18","2020-01-17","2020-01-17","2020-01-17","2020-01-17","2020-01-17","2020-01-16","2020-01-15","2020-01-15","2020-01-15","2020-01-15","2020-01-15","2020-01-15","2020-01-15"))
DF$Date <- as.Date(DF$Date)
# Order by date -> oldest first
DF <- DF[order(desc(DF$Date)),]
DF %>%
group_by(ItemNo, nvalue = abs(OrderAmount)) %>%
filter(!duplicated(OrderAmount)) %>%
filter(sum(OrderAmount) >= 0) %>%
ungroup() %>%
select(-nvalue)
E.g. I want the output for ItemNo 3245 to be
ItemNo OrderAmount Date
3245 -100 2020-01-20 #DELETE: Matched with 5. Row
3245 100 2020-01-18
3245 -100 2020-01-18 #DELETE: Matched with 6. Row
3245 200 2020-01-17
3245 100 2020-01-15 #DELETE: Matched with 1. Row
3245 100 2020-01-15 #DELETE: Matched with 3. Row