Approximate lookup in R

后端 未结 2 1712
迷失自我
迷失自我 2021-01-02 11:55

I have the following lookup table:

lkp <- data.frame(
         x=c(0,0.2,0.65,0.658,1.3,1.76,2.7), 
         y=c(1,1,1,0.942,0.942, 0.92, 0.89)
       )
<         


        
相关标签:
2条回答
  • 2021-01-02 12:36

    I do not think there is a ready function for this, but you could build one quite easily. E.g.:

    A function for getting "neighbourgs" (the name is a bit misleading, but the function works):

    get.neighbourgs <- function(vector, x) {
    diff <- vector-x
    if (any(diff==0)) {
        return(which(diff==0))
        } else {
            lower <- tail(which(diff<0), 1)
            return((lower-1):lower)
        }
    }
    

    It will return the exact "ID" if a value is found in vector, otherways it will return two "IDs" (two smaller values before that). It requires that your data is ordered! If not, you have to tweak it a bit. Examples of usage:

    > get.neighbourgs(lkp$x,1.3)
    [1] 5
    > get.neighbourgs(lkp$x,2)
    [1] 5 6
    

    Using this, a simple function can be built to get the mean of requiredy values, like:

    get.y <- function(df, x) {
        mean(df$y[get.neighbourgs(df$x, x)])
    }
    

    Examples:

    > get.y(lkp, 1.2)
    [1] 0.971
    > get.y(lkp, 2)
    [1] 0.931
    

    Hope that helps.

    0 讨论(0)
  • 2021-01-02 12:41

    Yes, it's called approx.

    > with(lkp, approx(x, y, xout=c(0.2, 2)))
    $x
    [1] 0.2 2.0
    
    $y
    [1] 1.0000000 0.9123404
    

    See ?approx for more information.

    0 讨论(0)
提交回复
热议问题