I have a dataframe looks like:
date   accumulated_visits
01-01    102
01-02    134
01-03    148
01-04    159
01-05    162
01-06    175
I want a function, which could find the nearest entry, given a specific visit number. For example, I want to find the date when accumulated visits reaches closing to 150. I expect return
01-03  148 
Is there a buildin function to handle that?
You can calculate absolute difference and use which.min to find the index of the smallest difference
df[which.min(abs(150-df$accumulated_visits)),]
#   date accumulated_visits
#3 01-03                148
OR, when accumulated_visits is sorted, you may also be able to use findInterval
df[findInterval(150, df$accumulated_visits),]
#   date accumulated_visits
#3 01-03                148
DATA
df = structure(list(date = c("01-01", "01-02", "01-03", "01-04", "01-05", 
"01-06"), accumulated_visits = c(102L, 134L, 148L, 159L, 162L, 
175L)), .Names = c("date", "accumulated_visits"), class = "data.frame", row.names = c(NA,
-6L))
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With