How to iterate through a dataframe and conditionally remove values?

I'm trying to iterate through a data frame and pull out values that were not in the previous group . So if I have:

group ID
1 1
1 2
1 3
2 4
2 5
2 1
3 6
3 5
3 1
3 3

Then these would be the rows that appear as new values not in the previous group This is my goal:

group ID
1 NA
2 4
2 5
3 6
3 3

Would this use a for loop and if_elif statement to dynamically remove from the prior number group?
Thank you!

Here is a start on how I wold do that.

library(tidyverse)
#> Warning: package 'tibble' was built under R version 4.1.2

DF <- data.frame(Group = c(1,1,1,2,2,2,3,3,3,3),
                 ID = c(1:5,1,6,5,1,3))
DF
#>    Group ID
#> 1      1  1
#> 2      1  2
#> 3      1  3
#> 4      2  4
#> 5      2  5
#> 6      2  1
#> 7      3  6
#> 8      3  5
#> 9      3  1
#> 10     3  3

FilterFunc <- function(G, DATA) {
  IDS <- DATA |> filter(Group == G - 1)
  DATA |> filter(Group == G, !ID %in% IDS$ID)
}
Groups = c(2,3)
map_dfr(Groups, FilterFunc, DATA = DF)
#>   Group ID
#> 1     2  4
#> 2     2  5
#> 3     3  6
#> 4     3  3

Created on 2022-03-09 by the reprex package (v2.0.1)

2 Likes

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.