# Function for a rolling join
# This will join df x to df y by (by.x = pre.y) and then will take post.y and treat that as the new by.x until exhausted 
# The join must be by a single column

rolling_join <- function(x, y, by.x, pre.y, post.y, id.name = "ID") {
  
 '%ni%' <- Negate('%in%')

#Initialise thw while loop with some parameters
Joining <- T
i<-0
colnames(x)[which(colnames(x) == by.x)] <- paste(id.name, i, sep = "_")

rolling.df <- x
hard.y <- y
fun.rename <- function(n) {paste0(n, "_", i+1)}

#Run the loop so long as there are no empty joins
while(Joining) {
  
  # Set up some variables
  rolling_id_add <- paste(id.name, i+1, sep = "_") 
  rolling_id <- paste(id.name, i, sep = "_")
  
# For the lookup add an integer to the IDs
  colnames(y)[which(colnames(hard.y) == pre.y)] <- rolling_id
  colnames(y)[which(colnames(hard.y) == post.y)] <- rolling_id_add 
  
  y <- rename_at(y, vars(colnames(y)[which(colnames(y) %ni% c(rolling_id, rolling_id_add))]), fun.rename)

  rolling.df <- dplyr::left_join(rolling.df, y)
  
  # Remove y and reset
  rm(y)
  y <- hard.y
  
  # Add to loop
  i <- i +1
  Joining <- ifelse(sum(!is.na(rolling.df[[rolling_id_add]])) == 0, FALSE, TRUE)  
  
}
return(rolling.df)
}

# # Example for how to join
# 
# # Make mock data
# predoc <- data.frame(ID = 100:299, Type = rep(c("Ins", "DA"), times = 100), Predoc_ID = c(0:99, sample(100:299, 100)))
# inc <- data.frame(ID = 0:99)
# 
# #Run Function
# test <- rolling_join(x = inc, y = predoc, by.x = "ID", pre.y = "Predoc_ID", post.y = "ID")