Vector position based on approximate match

I have a sorted vector

m<-c(1.1, 3.2, 3.6, 4, 4.6, 4.6, 5.6, 5.7, 6.2, 8.9)

I want to find the position of a value based on an approximate match. If the value does not exist in the vector, I would like the position of the immediately previous value

for exact match I would use

> match(4,m)
[1] 4

But if I do

> match(6,m)
[1] NA

What I would like to get in this example is 8(the position of the minimum previous value of 6, which is the position of 5.7, which is 8 )

Thank you in advance

+5
source share
5 answers

Use which.maxin conjunction with a vector subset, a 17-character solution:

which.max(m[m<=6]) # Edited to specify <=
[1] 8

, :

sum(m<=6) # Edited to specify <=
[1] 8

, TRUE 1 sum

+3

, , : findInterval ... , , , .

m <- c(1.1, 3.2, 3.6, 4, 4.6, 4.6, 5.6, 5.7, 6.2, 8.9)
# Find nearest (lower) index for both 4 and 6
findInterval(c(4,6), m) 
# [1] 4 8
+10

.

#v is a sorted vector and x is an item for which we want the exact or nearest lower match
lowSideMatch <- function(x, v) max(which(v <= x))

lowSideMatch(6, m)
[1] 8

lowSideMatch(4, m)
[1] 4
+3

which(), . .

x <- c(8,4,1,2,3,6,9)
find <- 6
pos <- which(abs(x-find) == min(abs(x-find)))
+1

- :

> m<-c(1.1, 3.2, 3.6, 4, 4.6, 4.6, 5.6, 5.7, 6.2, 8.9)

> ( index = length(m[m<=4]) )
[1] 4

> ( m[index] )
[1] 4

> ( index = length(m[m<=6]) )
[1] 8

> ( m[index] )
[1] 5.7
0

All Articles