在R中排序向量中查找值的索引 [英] Find index of value in a sorted vector in R

查看:293
本文介绍了在R中排序向量中查找值的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在R中有一个唯一整数的有序向量,并且我想找到最接近但小于或等于某个值的元素的索引.例如,对于向量4 8 15 16 23 42和搜索值17,我希望函数返回索引164.在Python中,我会使用 bisect 模块. R中有类似的东西吗?

I have an ordered vector of unique integers in R and I want to find the index of the element closest to but less than or equal to some value. For example, for the vector 4 8 15 16 23 42 and the search value 17, I would like the function to return 4, the index of 16. In Python, I would use bisect module. Is there anything similar in R?

推荐答案

Base R提供了

Base R provides findInterval which implements a binary search:

findInterval(17, c(4, 8, 15, 16, 23, 42))


@Khashaa已经在评论中提到了这一点.


@Khashaa already mentioned this in a comment.

这篇关于在R中排序向量中查找值的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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