Search code examples
rrangeintervalsbounds

R: define value as range / interval


I've looked around but could not find an answer that helps. I'm trying to set up a key-value table in R where the key is defined as range or interval so that I can do a look-up to find the value of any key that falls within the range / interval. To give a minimal example which does not work.

data.frame(key = c(range(0, 1),
                   range(1, 2)),
           value = c("A", 
                     "B"))

The data frame would not hold two rows but four since R is treating lower and upper interval bound as two separate values and recycle the value column to arrive at four rows. Besides this problem, I could also not find a range / interval function where I can define lower and upper bounds.

EDIT: The desired output would be a table like this:

key      value    
(0, 1)   "A"
(1, 2)   "B"

So I could do something like the following query for a value a: table$value[where a %in% table$key]


Solution

  • It is not really elegant but you can do this to make it practical and handy:

    df = data.frame(values=letters[1:2])
    df$keys=list(0:1, 1:2)
    #  values keys
    #1      a 0, 1
    #2      b 1, 2
    

    So that you do not need regex like when accessing the data with df$keys.