Get closest data from dataframe to R

I have a DataFrame as follows:

date   accumulated_visits
01-01    102
01-02    134
01-03    148
01-04    159
01-05    162
01-06    175

I need a function that can find the nearest record, given a specific visit number. For example, I want to find the date when accumulated visits reach close to 150. I expect a return

01-03  148 

Is there a built-in function to handle this?

+4
source share
1 answer

You can calculate the absolute difference and use which.minto find the least difference index

df[which.min(abs(150-df$accumulated_visits)),]
#   date accumulated_visits
#3 01-03                148

OR, when sorting accumulated_visits, you can also usefindInterval

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))
+6
source

Source: https://habr.com/ru/post/1672313/


All Articles