Reputation: 23660
Does anyone know of a generic R function for mapping data between ranges? I can't find anything but this seems a pretty essential basic function. e.g.
map = function(x, xmin=NULL, xmax=NULL, tmin=0, tmax=1, na.rm=FALSE){
if(is.null(xmin)) xmin = min(x)
if(is.null(xmax)) xmax = max(x)
x.range = xmax - xmin
t.range = tmax - tmin
((x - xmin) / x.range * t.range + tmin)
}
.. would by default normalise from input data range to [0,1], but could also use a custom input range or map to specific outputs:
> v = -5:5
> map(v)
[1] 0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0
> map(v, xmin=-10, xmax=10)
[1] 0.25 0.30 0.35 0.40 0.45 0.50 0.55 0.60 0.65 0.70 0.75
> map(v, tmax = 500)
[1] 0 50 100 150 200 250 300 350 400 450 500
Am I reinventing the wheel?
Upvotes: 2
Views: 192
Reputation: 77096
The scales package has one:
scales::rescale(v)
scales::rescale(v, from=c(-10, 10))
Upvotes: 3