首页 > 解决方案 > 如何找到最接近的值并返回另一列的值?

问题描述

dfdf<-data.frame(a= c(80,90,100,110,120),
b= c(500,400,300,200,100))
index= 102

如何在a列中找到最接近102的值并在b列中返回同一行的值?

预期产量:300

#attempt 1
index2<-min(abs(dfdf$a- index))
dfdf$b[dfdf$a- index==index2] # error sometimes positive values ​​and other times the value is negative

##output:
>numeric(0)

标签: rdataframesubset

解决方案


您可以使用findIntervalwhich 返回最接近值的索引;

dfdf[findInterval(102, dfdf$a),"b"]

 # [1] 300

推荐阅读