将值匹配到R中另一个数组中的最接近值 [英] Match values to nearest value in another array in R

查看:50
本文介绍了将值匹配到R中另一个数组中的最接近值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将一个值与其R中最接近的对应值匹配,并提取其索引.

I need to match a value to its nearest corresponding value in R and extract its index.

命令 FindInterval(value,array)实现了此目的,但仅在数组按升序排列时有效.

The command FindInterval(value,array) achieves this but only works if the array is in ascending order.

命令 match(value,array)仅在该值与数组中的一个完全匹配时才有效.

The command match(value,array) only works if the value provides an exact match to one in the array.

例如,

array <- c(0.1,0.5,0.6,0.3,0.9,1.4,0.45)
value <- 0.47

我想要一个命令,然后将该命令与最接近的相应 value (在此为0.45)匹配,并返回 index (在此为7).

I'd like a command which then matches this to the nearest corresponding value (here 0.45) and returns the index (here 7).

推荐答案

我们可以从 array 的每个元素中减去 value ,获得绝对差并获得索引位置使用 which.min 来确定最小值.

We can subtract value from every element of array , get the absolute difference and get the index position of minimum value using which.min.

which.min(abs(array - value))
# [1] 7

这篇关于将值匹配到R中另一个数组中的最接近值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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