Search code examples
rdplyrlookup-tables

assign parameters to continious variable based on look-up table


Assume we have the following values

x <- seq(18,35, by = 0.5)

And a look-up table with parameters that I want to assign to x. x1 and x2 mark the minimum and maximum range for the values

    # A tibble: 6 x 4
     x1    x2 intercept   slope
  <dbl> <dbl>     <dbl>   <dbl>
1  -Inf  19.8     1.76   0.0404
2  19.8  26.6    -9.45   0.606 
3  26.6  27.9     0.474  0.230 
4  27.9  31.0    37.6   -1.10  
5  31.0  31.5   148.    -4.66  
6  31.5  Inf    -5.46   0.209 

How would I assign the intercept and slope parameters to the respective x values? I am actually quite familiar with dplyr but I can't get my head around to do this. Also, I tried looking for other look-up table questions on stackoverflow, but I couldnt find any helpful solution.

My expected output would look like this:

x    intercept slope
18.0  1.76   0.0404
18.5  1.76   0.0404
19.0  1.76   0.0404
19.5  1.76   0.0404
20.0  -9.45  0.606
20.5  -9.45  0.606
....

Data:

structure(list(x1 = c(-Inf, 19.7655265277778, 26.6391981944444, 
27.9157038888889, 30.961035, 31.4874096527778), x2 = c(19.7655265277778, 
26.6391981944444, 27.9157038888889, 30.961035, 31.4874096527778, 
Inf), intercept = c(1.76419323634379, -9.44859660351845, 
0.47371274205448, 37.6478699886245, 147.812568102278, -5.4621312700186
), slope = c(0.0404262603296852, 0.606495044017168, 0.230158004169582, 
-1.1001218987118, -4.66067451640575, 0.208662384114064)), row.names = c(NA, 
-6L), class = c("tbl_df", "tbl", "data.frame"))

Solution

  • You can take help of cut -

    cbind(x, df[cut(x, c(-Inf, df$x2), labels = FALSE), -(1:2)])
    #We can also use `x1` similarly
    #cbind(x, df[cut(x, c(df$x1, Inf), labels = FALSE), -(1:2)])
    
    #      x   intercept       slope
    #1  18.0   1.7641932  0.04042626
    #2  18.5   1.7641932  0.04042626
    #3  19.0   1.7641932  0.04042626
    #4  19.5   1.7641932  0.04042626
    #5  20.0  -9.4485966  0.60649504
    #6  20.5  -9.4485966  0.60649504
    #7  21.0  -9.4485966  0.60649504
    #8  21.5  -9.4485966  0.60649504
    #9  22.0  -9.4485966  0.60649504
    #10 22.5  -9.4485966  0.60649504
    #...
    #...