Clip values between a minimum and maximum allowed value in R

前端 未结 4 1841
不思量自难忘°
不思量自难忘° 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 21:05

    Here's one function that will work for both vectors and matrices.

    myClip <- function(x, a, b) {
        ifelse(x <= a,  a, ifelse(x >= b, b, x))
    }
    
    myClip(x = 0:10, a = 3,b = 7)
    #  [1] 3 3 3 3 4 5 6 7 7 7 7
    
    myClip(x = matrix(1:12/10, ncol=4), a=.2, b=0.7)
    # myClip(x = matrix(1:12/10, ncol=4), a=.2, b=0.7)
    #      [,1] [,2] [,3] [,4]
    # [1,]  0.2  0.4  0.7  0.7
    # [2,]  0.2  0.5  0.7  0.7
    # [3,]  0.3  0.6  0.7  0.7
    

    And here's another:

    myClip2 <- function(x, a, b) {
        a + (x-a > 0)*(x-a) - (x-b > 0)*(x-b)
    }
    
    myClip2(-10:10, 0, 4)
    # [1] 0 0 0 0 0 0 0 0 0 0 0 1 2 3 4 4 4 4 4 4 4
    

提交回复
热议问题