比较允许特定误差范围的值 [英] Compare values allowing for a specific margin of error

查看:45
本文介绍了比较允许特定误差范围的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在比较数字或向量时,R 中是否有任何允许误差范围的书面函数?如果两个值在指定的可容忍误差范围内,则 x==y 将评估为 TRUE.

Are there any written functions in R that allow for a margin of error when comparing numbers or vectors? x==y would evaluate to TRUE if the two values were within a specified tolerable error margin.

例如,如果目标值为 77 并且我允许的误差幅度为 5%,那么问这个问题是否 x==77?如果 x 在 77 左右的 5% 误差范围内,则计算结果为 TRUE,即 x 在 73.15 和 80.85 之间的任何值都将计算为 TRUE.

Example if the target value is 77 and my allowable margin of error was 5%, asking the question does x==77? would evaluate to TRUE if x is within a 5% margin of error around 77, i.e. any values of x between 73.15 and 80.85 would evaluate to TRUE.

我可以修正一个函数来进行=="比较,但无法提出一个解决方案来围绕每个目标值建立一个可接受"范围,这样如果我允许的误差幅度为 5%,任何落在 tgt 值 +/- 5% 范围内的 dta 元素都将评估为 TRUE.

I can right a function to do the "==" comparison but couldn't come up with a solution that builds an "acceptance" range around each of the target values so that if my allowable margin of error was 5%, any of the dta elements that falls within +/- 5% of tgt values would evaluate to TRUE.

tgt <- c(45,77,92)
dta <- c(33,41,44,60,68,71,77,78,87,95)
sapply(tgt, function(i) i==dta)

这将每个 tgt 与每个 dta 进行比较.唯一返回 TRUE 的比较是将 77 与 77 进行比较.我必须围绕每个 tgt 元素构建一个范围,然后将每个 dta 元素与该范围进行比较,只要任何 dta 元素落在创建的任何范围内,就会返回 true.当我开始构建范围时,我感到非常困惑.当 44 与 45 相比时,我正在寻找的结果将评估为真,因为它短不到 5%,同样,78 足够接近 77 以评估为真以及 95 到 92.

This compares each of tgt to each of dta. The only comparison that returns TRUE is when 77 is compared to 77. I would have to build a range around each of tgt elements then compare each of dta elements to that range returning true whenever any of dta elements falls inside any of the ranges created. As I started building the ranges I got so confused. The result I am looking for would evaluate to true when 44 is compared to 45 as it's short by less than 5%, similarly 78 is close enough to 77 to evaluate to true as well as 95 to 92.

推荐答案

neighbour <- function(x, y, tol=0.1){
  sapply(x, function(.x) {.tol <- tol * pmax(.x, y) ; abs(.x - y) <= .tol})
}

tgt <- c(45,77,92)
dta <- c(33,41,44,60,68,71,77,78,87,95)

neighbour(x=tgt, y=dta)

这篇关于比较允许特定误差范围的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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