【问题标题】:How to find the closest value and return the value of the other column?如何找到最接近的值并返回另一列的值?
【发布时间】:2020-05-06 17:31:24
【问题描述】:
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)

【问题讨论】:

  • 你想用确定的最接近的数字填充整个列吗?如果是,当你有两个最接近的数字时会发生什么?
  • 不,我只想返回“b”列的值,它与“a”列的值在同一行,更接近 102。

标签: r dataframe subset


【解决方案1】:

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

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

 # [1] 300

【讨论】:

  • 只是出于好奇,如果两个 obs 之间的差异相同且非零 findinterval 采用第一个,而如果为零则选择第二个。为什么是这样? (我希望我没有忽略任何愚蠢的事情)
  • @desval 如果您运行?findInterval,它将解释如何使用可选参数rightmost.closedall.inside 来控制该行为。
【解决方案2】:

或者按照你已经尝试过的:

dfdf$b[which.min(abs(index - dfdf$a))]
# [1] 300

附带说明(如果有两个匹配项,不确定您的结果应该是什么):

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


dfdf$b[which.min(abs(index - dfdf$a))]
# [1] 300

dfdf[findInterval(index, dfdf$a),"b"]
# [1] 200

另一个有趣的例子:

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

dfdf$b[which.min(abs(index - dfdf$a))]
# [1] 400

dfdf[findInterval(index, dfdf$a),"b"]
# [1] 400

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-22
    • 1970-01-01
    相关资源
    最近更新 更多