Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find nearest smaller number

Tags:

r

numeric

vector

I have a vector of numbers

f <- c(1, 3, 5, 8, 10, 12, 19, 27)

I want to compare the values in the vector to another number, and find the closest smaller value.

For example, if the input number is 18, then the closest, smaller value in the vector is 12 (position 6 in the vector). If the input is 19, then the result should be the value 19, i.e. the index 7.

like image 776
heinheo Avatar asked May 18 '15 22:05

heinheo


People also ask

How do you find the nearest smaller number in an array?

Given an array of integers, find the nearest smaller number for every element such that the smaller element is on left side. Examples: Input: arr[] = {1, 6, 4, 10, 2, 5} Output: {_, 1, 1, 4, 1, 2} First element ('1') has no element on left side.

Is it possible to find the closest smaller value from random numbers?

It is much more difficult to find the closest smaller value when your list of numbers is random and not ordered, but it is possible. Let's explore how to do this. If you want to follow along with this tutorial, download the example spreadsheet.

How do you find the nearest smallest value in Excel?

Enter formula in cell E2. Press Enter. The closest smallest value will be retrieved from the data. Enter formula in cell E2. Press Enter. The closest smallest value will be retrieved from data.

How do I find the next smaller value in a list?

In cell C2, we've created the following formula that uses the LARGE function with the COUNTIF function to find the next smaller value in the list of material lengths: This formula will look at the value in B2 and find the next smaller value in the range $A$2:$A13. Notice that we used absolute referencing on the range $A$2:$A13 in the formula.


4 Answers

I think this answer is pretty straightforward:

f <- c(1,3,6,8,10,12,19,27)
x <- 18

# find the value that is closest to x
maxless <- max(f[f <= x])
# find out which value that is
which(f == maxless)
like image 84
John Avatar answered Oct 11 '22 15:10

John


If your vector f is always sorted, then you can do sum(f <= x)

f <- c(1,3,6,8,10,12,19,27)

x <- 18
sum(f <= x)
# [1] 6

x <- 19
sum(f <= x)
# [1] 7
like image 37
Gregor Thomas Avatar answered Oct 11 '22 14:10

Gregor Thomas


Try this (not a perfect solution)

x<-c(1,3,6,8,10,12,19,27)
showIndex<-function(x,input){
 abs.diff<-abs(x-input)
 index.value<-unique(ifelse(abs.diff==0,which.min(abs.diff),which.min(abs.diff)-1))
return(index.value)
 }
 showIndex(x,12)
    [1] 6
showIndex(x,19)
[1] 7
like image 4
user227710 Avatar answered Oct 11 '22 16:10

user227710


You could try:

x <- 18
f <- c(1,3,6,8,10,12,19,27)

ifelse(x %in% f, which(f %in% x), which.min(abs(f - x)) - 1)

That way if x is not in f, it will return the nearest previous index. If x is in f, it will return x index.

like image 2
Steven Beaupré Avatar answered Oct 11 '22 15:10

Steven Beaupré