r - 如何找到最接近的值并返回另一列的值?
问题描述
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)
解决方案
您可以使用findInterval
which 返回最接近值的索引;
dfdf[findInterval(102, dfdf$a),"b"]
# [1] 300
推荐阅读
- php - lumen array_key_exists() 贬值了,那么如何使用像 isset() 或 property_exists() 这样的替代方法来排列?
- c# - 在 Razor 页面中单击按钮时查看组件刷新
- reactjs - react useState 这样使用会导致无法输入中文,为什么呢?
- docker - 当我在 docker 中运行我的系统 .net 核心应用程序时,抛出错误为“此平台不支持 System.Data.OleDb”
- python - 甚至我所有的实例设置和 Dockerfile 都没有找到 nginx 404
- python - Python:基于组求和并将其显示为附加列
- duplicates - 仅选择结果中多行中的第一行(不是全部)
- ruby-on-rails - 无法在生产环境中访问 Rails 控制台中的不同数据库
- regex - 如何在 htaccess 中使用 rewriteRule
- spring - spring data r2dbc @createdBy 字段设置