Given two values x
and b
, I want a function to clamp x
to fall within [-b, b]
. In particular:
- If
x
is less than or equal to-b
, then the function returns-b
; - If
x
is greater than-b
and less thanb
, then the function returnsx
; - If
x
is greater than or equal tob
, then the function returnsb
.
In R I wrote the following function truncfn
. Only part of this function works. Where did I make mistake? Is there an easier way to do this?
b <- 5
truncfn <- function(x){
if((x<(-b))||(x==-b)) -b
if((x>(-b))&&(x<b)) x
if((x>b)||(x==b)) b
}
truncfn(10)
5
truncfn(4)
truncfn(-10)