中的R的最小和最大允许值之间的值剪辑(Clip values between a minimum a

2019-07-05 06:04发布

Mathematica中有命令Clip[x, {min, max}]这使xmin<=x<=maxminx<min和和maxx>max ,参见

http://reference.wolfram.com/mathematica/ref/Clip.html ( 镜 )

什么是R中实现这一目标的最快的方法? 理想情况下,应该是一个函数,可列,最好应该在一个单一的值,向量,矩阵或数据帧工作...

欢呼声,汤姆

Answer 1:

Rcppclamp为此:

cppFunction('NumericVector rcpp_clip( NumericVector x, double a, double b){
    return clamp( a, x, b ) ;
}')

这里是展示它如何执行对讨论的其他方法快速基准:

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    


Answer 2:

下面是嵌套的方法pminpmax设置范围:

 fenced.var <- pmax( LB, pmin( var, UB))

这将是很难找到更快的方法。 包裹在一个函数,默认范围的3和7:

fence <- function(vec, UB=7, LB=3) pmax( LB, pmin( vec, UB))

> fence(1:10)
 [1] 3 3 3 4 5 6 7 7 7 7


Answer 3:

这里有一个功能,将两个向量和矩阵的工作。

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

而这里的另一个:

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


Answer 4:

我相信这将是clamp()raster包。

library(raster)
clamp(x, lower=-Inf, upper=Inf, ...)


文章来源: Clip values between a minimum and maximum allowed value in R