Jake Parker
Jake Parker

Reputation: 241

How to find out all integers between two real numbers using R

Problem: how can I write a function that receives a and b as inputs and returns all integers inbetween them. So, assuming we have a function called integers_inbetween that behaves like this, we should expect the following examples:

# Returns an array of integers in between a and b
integers_inbetween(1, 4)
[1] 2 3

and

# Returns an array of integers in between a and b
integers_inbetween(4, 1)
[1] 2 3

And

# Returns NULL if there are no integers inbetween a and b
integers_inbetween(3.5, 4)
[1] NULL

How can one implement that logic in R?

Upvotes: 5

Views: 1324

Answers (3)

eduardokapp
eduardokapp

Reputation: 1751

This solution should work. I'm assuming the function should work if a > b and also if not. The way I wrote it, if after rounded a == b, the function returns NULL.

inbetween_integers <- function(a, b) {
    a <- round(a)
    b <- round(b)
    dist_ab <- abs(a-b)
    if (dist_ab <= 1)
        return(NULL)
    if (b < a)
        return(seq.int(from = b + 1, length.out = dist_ab - 1))
    return(seq.int(from = a + 1, length.out = dist_ab - 1))
}

Upvotes: 3

GuedesBF
GuedesBF

Reputation: 9868

This works regardless of the order of arguments. First this function sorts the arguments, then determines the minimum and maximum values in the sequence (exclusive of integer boundaries), then returns the sequence as requested.

integers_in_between<-function(x,y){
        values<-sort(c(x,y))
        minimum<-ifelse(ceiling(values[1])==values[1], ceiling(values[1])+1, ceiling(values[1]))
        maximum<-ifelse(floor(values[2])==values[2], floor(values[2])-1, floor(values[2]))
        if(maximum-minimum<0){
                NULL
        }else{
                minimum:maximum
        }
}

Upvotes: 1

ThomasIsCoding
ThomasIsCoding

Reputation: 102251

You can try the code below

inbetween_integers <- function(a, b) {
  u <- sort(c(a, b))
  res <- setdiff(ceiling(u[1]):floor(u[2]), c(a, b))
  if (!length(res)) {
    NULL
  } else {
    res
  }
}

and you will see

> inbetween_integers(1, 4)
[1] 2 3

> inbetween_integers(4, 1)
[1] 2 3

> inbetween_integers(3.5, 4)
NULL

Upvotes: 1

Related Questions