# Lerp function in base R?

Is there a base R function that lerps between two numbers?

i.e. a function that would let you ask 'whats the number 50% between 10 and 20 and would return 15

Basically an inbuilt version of this:

``````lerp <- function(num1, num2, fraction){
(num2-num1)*fraction+num1
}
``````
``````median(c(10,20))
#> [1] 15
``````

Apologies for the lack of clarity. I meant is there an inbuilt function that would take any fraction, and return the appropriate number? (not just 50%)

Lack of clarity was on my endâ€”focusing on the answer to the example, not the question.

I haven't been able to find a function in `base` that does this.

Genralise `median` to `quantile`, and it'll solve your question.

``````lerp <- function(num1, num2, fraction){
(num2-num1)*fraction+num1
}

for (i in seq(0, 1, 0.01))
{
a <- lerp(10, 20, i)
b <- quantile(c(10, 20), i)
if (isFALSE(all.equal(a, b))) {
print(c(i, a, b))
}
}
``````

But nothing's wrong your function, as far as I can see. You can continue to use that as well.

1 Like

hacky but...

``````nums <- c(10,23)
f <- .65

lerp <- function(num1, num2, fraction){
(num2-num1)*fraction+num1}
lerp(nums[1],nums[2],f)

approx(1:2,
nums,
n = 3,
f = f,
method = "constant")\$y[[2]]``````

Seconding the nomination of `quantile`, so the one-line answer to the OQ is `quantile(c(num1,num2), fraction)` will give the right answer.

3 Likes

This topic was automatically closed 7 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.