Search code examples
ralgorithmclipping

Clipping elements in a long vector to +/-threshold


I am writing program in R. I stuck here.

I have vector like

X=c(84.05, 108.04, 13.95, -194.05, 64.03, 208.05, 84.13, 57.04)

I want to get a vector after replacing all elements of this vector which are >180 by 180 and all elements which are less than <-180 by -180.

Like I want to get,

X=c(84.05, 108.04, 13.95,-180, 64.03, 180, 84.13, 57.04)

How to do this??

The vector which I am working is very large.


Solution

  • Try using pmin

    > pmin(abs(X), 180)*sign(X)
    [1]   84.05  108.04   13.95 -180.00   64.03  180.00   84.13   57.04
    

    Benchmark

    > Jilber <- function() pmin(abs(X), 180)*sign(X)
    > MrFlick <- function() pmin(pmax(X, -180), 180)
    > user1317221_G <- function() ifelse(X < -180,-180, ifelse(X > 180, 180, X))
    > benchmark(replications=50000,
    +           Jilber(),
    +           MrFlick(),
    +           user1317221_G(), 
    +           columns=c('test', 'elapsed', 'relative'))
                 test elapsed relative
    1        Jilber()   0.835    1.000
    2       MrFlick()   1.297    1.553
    3 user1317221_G()   1.709    2.047