检查数字是否在两个之间

时间:2018-12-06 08:41:35

标签: r range

我正在寻找一个函数来验证数字是否在其他两个数字之间。我还需要控制是否要进行严格的比较(

我知道between()中的函数dplyr。但是,我必须知道上限和下限数字。

MyNumber = 8
First = 2
Second = 10
# This will return TRUE
between(MyNumber, lower =  First, upper =  Second)
# But this will return FALSE
between(MyNumber, lower =  Second, upper =  First)
# This will return TRUE. I want it to return FALSE
First = 8
between(MyNumber, lower =  First, upper =  Second)

无论顺序如何,我都需要一个返回TRUE的函数。

4 个答案:

答案 0 :(得分:4)

类似:

between2 <- function(number,bounds) { number > min(bounds) & number < max(bounds)} 
between2(8, c(2,10))
[1] TRUE
between2(8, c(10,2))
[1] TRUE

此功能还可以处理您添加的条件

between2(8,c(8,10))
[1] FALSE

答案 1 :(得分:4)

您可以使用简单的算法做到这一点:

between <- function(number, first, second) { (first - number) * (second - number) < 0 }

以下是一些示例输出:

> between(8, 2, 10)
[1] TRUE
> between(8, 10, 2)
[1] TRUE
> between(8, 10, 12)
[1] FALSE
> between(8, 1, 2)
[1] FALSE

答案 2 :(得分:2)

一旦您%in%:,就可以将firstlast功能一起使用:

first <- 2
last <- 10
number <- 8

number %in% first:last 
[1] TRUE

first <- 10
last <- 2
number <- 8
number %in% first:last
[1] TRUE


first <- 10
last <- 12
number <- 8
number %in% first:last
[1] FALSE

first <- 12
last <- 10
number <- 8
number %in% first:last
[1] FALSE

在函数中,strict可让您考虑或不严格进行比较:

my_between <- function(n, f, l, strict = FALSE) {
  if (!strict) { 
    n %in% f:l # if strict == FALSE (default)
  } else {
    n %in% (f+1):(l-1) # if strict == TRUE 
  }
}

my_between(8, 2, 10)

答案 3 :(得分:1)

怎么了

f_between <- function (num, L, R) num>=min(L,R) & num<=max(L,R)

f_between(8, 2, 10)
#[1] TRUE
f_between(6, 6, 10)
#[1] TRUE
f_between(2, -10, -2)
#[1] FALSE
f_between(3, 5, 7)
#[1] FALSE