# The correspondence python function; interp in R to get the same results

Hello all,
what is the correspondence to python function; “interp” in R to get the same results below

``````>> xp = [1, 2, 3]
>> fp = [3, 2, 0]
>> np.interp(2.5, xp, fp)
1.0
>> np.interp([0, 1, 1.5, 2.72, 3.14], xp, fp)
array([3.  , 3.  , 2.5 , 0.56, 0.  ])
>> UNDEF = -99.0
>> np.interp(3.14, xp, fp, right=UNDEF)
-99.0
``````

There is probably a better way to write this and I am not sure it gives all the behavior you want.

``````xp = c(1, 2, 3)
fp = c(3, 2, 0)
MyFunc <- function(Trg, X1, Y1, left =NULL, right = NULL) {
Y1 <- Y1[order(X1)]
X1 <- sort(X1)

InnerFunc <- function(Val) {
if(Val < min(X1)) {
if(is.null(left)) {
return(Y1[1])
} else {
return(left)
}
}
if(Val > max(X1)) {
if(is.null(right)) {
return(Y1[length(Y1)])
} else return(right)
}
Idx <- which(Val <= X1)[1]
if (Idx == 1) return(Y1[1])
slope <- (Y1[Idx ] - Y1[Idx - 1])/(X1[Idx] - X1[Idx - 1])
Y1[Idx - 1] + slope * (Val - X1[Idx - 1])
}
sapply(X = Trg, FUN = InnerFunc)
}

MyFunc(c(0, 1, 1.5, 2.72, 3.14), xp, fp)
[1] 3.00 3.00 2.50 0.56 0.00

MyFunc(c(0, 1, 1.5, 2.72, 3.14), xp, fp, right = -99.9, left = -23)
[1] -23.00   3.00   2.50   0.56 -99.90
``````
1 Like

It's really perfect, many thanks for your help, it is done

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.