Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get nearest data from dataframe in R [duplicate]

Tags:

dataframe

r

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?

like image 971
lserlohn Avatar asked Mar 15 '17 03:03

lserlohn


1 Answers

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))
like image 197
d.b Avatar answered Nov 02 '22 03:11

d.b