Find a row that matches a range of values

I am trying to get a column importantvalfor a number that is within range. I have no idea how to start this, who has any ideas?

data<-data.frame(lower=c(1,4,6,7,7),upper=c(3,5,7,8,9),importantval=c(99,98,97,96,95))
vals<-c(1.14,3.5,7.2,19)

> data
  lower upper importantval
1     1     3           99
2     4     5           98
3     6     7           97
4     7     8           96
5     7     9           95

exit goal

# 1.14 99
# 3.5 NA
# 7.2 96 <--return the smalller interval (from 7 to 8 is smaller than 7 to 9)
# 19 NA <--doesnt exist so return NA
+4
source share
1 answer

A simple one lapplywill do the trick. Line identification is relatively simple. The if statement takes only a shorter interval, when several values ​​work, it’s a little harder to understand, but basically, if there are several possibilities, I take a line where the interval is equal to the smallest possible interval.

foo <- function(i) {
  res <- data[data$lower < i & data$upper > i, ]
  if (nrow(res) > 1) {
    res <- res[which(res$upper - res$lower == min(res$upper - res$lower)), ]
  }
  if (nrow(res) == 0) return(NA)
  return(res$importantval)
}

results <- data.frame(vals, sapply(vals, foo))

This assumes that there are no intervals of the same length. If possible, you can add return(min(res$importantval))at the end to get only a lower value.

, :

results <- lapply(vals, foo)
names(results) <- vals
+2

Source: https://habr.com/ru/post/1652894/


All Articles