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