In Mathematica there is the command Clip[x, {min, max}]
which gives x
for min<=x<=max
, min
for x<min
and and max
for x>max
, see
http://reference.wolfram.com/mathematica/ref/Clip.html (mirror)
What would be the fastest way to achieve this in R? Ideally it should be a function that is listable, and should ideally work on either a single value, vector, matrix or dataframe...
cheers, Tom
I believe that would be
clamp()
from theraster
package.Rcpp
hasclamp
for this:Here is a quick benchmark showing how it performs against other methods discussed :
Here's one function that will work for both vectors and matrices.
And here's another:
Here's a method with nested
pmin
andpmax
setting the bounds:It will be difficult to find a method that is faster. Wrapped in a function that defaults to a range of 3 and 7: