Clip values between a minimum and maximum allowed value in R

前端 未结 4 1844
不思量自难忘°
不思量自难忘° 2020-12-13 20:34

In Mathematica there is the command Clip[x, {min, max}] which gives x for min<=x<=max, min for x

4条回答
  •  心在旅途
    2020-12-13 20:56

    Here's a method with nested pmin and pmax setting the bounds:

     fenced.var <- pmax( LB, pmin( var, UB))
    

    It will be difficult to find a method that is faster. Wrapped in a function that defaults to a range of 3 and 7:

    fence <- function(vec, UB=7, LB=3) pmax( LB, pmin( vec, UB))
    
    > fence(1:10)
     [1] 3 3 3 4 5 6 7 7 7 7
    

提交回复
热议问题