Question

I'm trying to "bin" some randomly generated numbers between an interval defined between to adjacent values within a vector of values I previously have. So essentially, I have the following:

vectorA containing 101 values ranging from 101 to 0. I generate a random number called x. Now I'd like to see which interval, between two numbers adjacent to each other in vectorA does it belong to? Finally, once it has found the interval, I return those two values.

I have an if statement going; if (x < vectorA[k] | x > vectorA[k+1]), under a for-loop so the if-statement can go through all the increments of vectorA.

I want to stay away from R's breaks method because I need to grab the actual bin interval values and use them to compute something.

Was it helpful?

Solution

As Ben pointed out, findInterval is your friend.

vectorA has to be sorted in ascending order though.

findRange <- function(x, v) {
  i <- findInterval(x, v)
  list(from=i, to=i+1L)
}

v <- seq(1, 100, 10) # Must be sorted in ascending order!
x <- runif(10, 1, 100)
findRange(x, v)

If your vectorA is sorted high to low, you'd have to reverse it and modify the indexes:

iRev <- findInterval(x, rev(vectorA))
iLow <- length(vectorA) - iRev
iHigh <- iLow + 1L
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top