paul_on_pc
paul_on_pc

Reputation: 139

How to test if a number is in a certain range to a number in the list

Imagine having a number x = 10 and a list of numbers list = (1, 8, 5). Now I want my code to return "True" if the number is in a 2 point range to this list.

Which in this example should return true as the number 10 is in a 2 number range to 8, which is in the list.

More examples in case I was not precise enough:

x = 10, list = (1,7,5) -> False
x = 8, list = (1,8,5) -> True

Upvotes: 0

Views: 52

Answers (2)

Jan
Jan

Reputation: 5254

Set same sample data

mylist <- list(1, 8, 5)

This is how you test it (and - for the record - you said it's a list of values, so I take your word on that):

x <- 10 
x <= max(unlist(mylist))+2 & x >= min(unlist(mylist))-2
# TRUE
x <- 11
x <= max(unlist(mylist))+2 & x >= min(unlist(mylist))-2
# FALSE

Upvotes: 0

dww
dww

Reputation: 31452

we can use

in.range = function(x, l, Range) {
  any(abs(l-x) <= Range)
}

in.range(10, c(1,8,3), 2)
# [1] TRUE
in.range(10, c(1,7,3), 2)
# [1] FALSE

Upvotes: 5

Related Questions