0

I know we can find the index of row of 11500 in column a with

which(df$a == 11500)

how about if I want to find the closest and less than a row index for a particular column value.

fore example in column a :

  a
  1
  2 
  5       
 10

what is row number of a value which is less than or equal to 8 and closest to it? answer: the value is 5 and row index that I am trying to find is 3.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213

1 Answers1

1

Here is one way to do it

a <- c(1, 2 , 5,  10)
val <- 8

vals <- a - val
which(a == max(a[vals <= 0]))
#[1] 3

If a is always sorted we can also use findInterval

max(which(findInterval(a, val, left.open = TRUE) == 0))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • thank you so much , could you plz check this post and see if you can help, https://stackoverflow.com/questions/57894230/how-to-divide-dataset-to-test-and-train-whit-respect-of-a-group/57895872?noredirect=1#comment102291913_57895872 –  Sep 15 '19 at 01:54