在其他列中搜索最接近的值 [英] Searching the closest value in other column

查看:18
本文介绍了在其他列中搜索最接近的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个两列的数据框

Suppose we have a data frame of two columns

 X    Y 
 10  14 
 12  16   
 14  17  
 15  19   
 21  19

Y 的第一个元素是 14,最接近(或相同)的值是 14(X 的第三个元素).类似地,Y 的下一个元素最接近 15,即 X 的第 4 个元素

The first element of Y that is 14, the nearest value (or same) to it is 14 (which is 3rd element of X). Similarly, next element of Y is closest to 15 that is 4th element of X

所以,我想要的输出应该是

So, the output I would like should be

3
4
4
5
5

由于我的数据很大,你能给我一些关于系统/正确代码的建议吗?

As my data is large, Can you give me some advice on the systemic/proper code for doing it?

推荐答案

你可以试试这段代码:

apply(abs(outer(d$X,d$Y,FUN = '-')),2,which.min)
# [1] 3 4 4 5 5

这里,abs(outer(d$X,d$Y,FUN = '-')) 返回 d$X 之间的无符号差异矩阵code>d$Yapply(...,2,which.min) 将逐行返回最小值的位置.

Here, abs(outer(d$X,d$Y,FUN = '-')) returns a matrix of unsigned differences between d$X and d$Y, and apply(...,2,which.min) will return position of the minimum by row.

这篇关于在其他列中搜索最接近的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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