Clipping elements in a long vector to +/-threshold

100 views Asked by At

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.

2

There are 2 answers

7
Jilber Urbina On BEST ANSWER

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
0
user1317221_G On
ifelse(X < -180,-180, ifelse(X > 180, 180, X))