I have a dataframe which I would like to add a column identifying the closest value to the respective column from only all previous values ignoring itself.
I found a closest value function but am unsure how to limit it to only previous rows. In the following example I would like to find the closest Revenue value considering only previous rows.
set.seed(1)
df<-data.frame(id=c(1:20),Revenue=sample(20))
closest<-function(xv,sv){
xv[which(abs(xv-sv)==min(abs(xv-sv)))] }