-1

I have a formula. When r calculates the value, if the result is between 0 and 1, the function should return the computed value. But, if it is below 0, the function should return 0, and if it is above 1, the function should return 1.

Is there an efficient way to do it without using the if function?

I found a javascript code that does what I want to do in R. Here it is:

clip = (a, b, t) => Math.min(Math.max(t, a), b)

1 Answers1

0

In Javascript, you could guard with Math.min and Math.max with lower and upper bound.

const
    x = (y, z) => Math.max(Math.min(y - z, 1), 0);

console.log(x(1, 2));   // 0
console.log(x(2, 0));   // 1
console.log(x(1, 0.5)); // 0.5
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392