将值限制在R中的最小和最大允许值之间 [英] Clip values between a minimum and maximum allowed value in R
本文介绍了将值限制在R中的最小和最大允许值之间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Mathematica中,有命令Clip[x, {min, max}]
给出x
的x
,x<min
的min
和x>max
的max
,请参见
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 (镜像)
在R中实现这一目标的最快方法是什么?理想情况下,它应该是可列出的函数,并且理想情况下,它应该在单个值,向量,矩阵或数据帧上工作...
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...
欢呼声, 汤姆
推荐答案
Rcpp
为此具有clamp
:
cppFunction('NumericVector rcpp_clip( NumericVector x, double a, double b){
return clamp( a, x, b ) ;
}')
这里是一个快速基准测试,显示了它相对于其他讨论的方法的性能:
Here is a quick benchmark showing how it performs against other methods discussed :
pmin_pmax_clip <- function(x, a, b) pmax(a, pmin(x, b) )
ifelse_clip <- function(x, a, b) {
ifelse(x <= a, a, ifelse(x >= b, b, x))
}
operations_clip <- function(x, a, b) {
a + (x-a > 0)*(x-a) - (x-b > 0)*(x-b)
}
x <- rnorm( 10000 )
require(microbenchmark)
microbenchmark(
pmin_pmax_clip( x, -2, 2 ),
rcpp_clip( x, -2, 2 ),
ifelse_clip( x, -2, 2 ),
operations_clip( x, -2, 2 )
)
# Unit: microseconds
# expr min lq median uq max
# 1 ifelse_clip(x, -2, 2) 2809.211 3812.7350 3911.461 4481.0790 43244.543
# 2 operations_clip(x, -2, 2) 228.282 248.2500 266.605 1120.8855 40703.937
# 3 pmin_pmax_clip(x, -2, 2) 260.630 284.0985 308.426 336.9280 1353.721
# 4 rcpp_clip(x, -2, 2) 65.413 70.7120 84.568 92.2875 1097.039
这篇关于将值限制在R中的最小和最大允许值之间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文