查找最近的较小数字 [英] Find nearest smaller number

查看:50
本文介绍了查找最近的较小数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数字向量

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.

例如,如果输入数字是 18,那么向量中最接近的较小值是 12(向量中的位置 6).如果输入是 19,那么结果应该是值 19,即索引 7.

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.

推荐答案

我认为这个答案很简单:

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)

这篇关于查找最近的较小数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆