my solution:
library(tidyverse)
example_df <- tibble::tribble(
~id, ~re_enter_id, ~date, ~score,
101L, NA, "01.1.2021", 60L,
102L, 101L, "12.1.2021", 65L,
103L, 102L, "17.1.2021", 70L,
104L, 103L, "18.1.2021", 68L,
105L, NA, "25.1.2021", 81L,
106L, NA, "03.1.2021", 55L,
107L, NA, "10.1.2021", 67L,
108L, 107L, "11.1.2021", 69L,
109L, NA, "09.1.2021", 85L
)
#make a simpler table to work with
edf <- example_df %>% select(id,re_id=re_enter_id)
get_related_ids <- function(x){
no_change <- TRUE
(last_scan <- filter(edf,id==x| re_id==x) %>% unlist %>% unique()%>%na.omit)
if(length(last_scan)==0)
stop("invalid id given")
while (no_change) {
new_scan <- filter(edf,id %in% last_scan | re_id %in% last_scan)%>% unlist %>% unique() %>% na.omit() %>% as.integer()
no_change <- !identical(new_scan,last_scan)
last_scan <- new_scan
}
return(last_scan)
}
#testing on all ids
map(101:109, ~get_related_ids(.)) %>% set_names(101:109)