Learn R Programming

plotlsirm (version 0.1.3)

rescale_to_range: Rescale a numeric vector to a new range

Description

Linearly transforms the values in x so they fall within a specified interval. Useful, for example, when mapping latent-space coordinates to aesthetic ranges (point sizes, color scales, etc.) in a plot.

Usage

rescale_to_range(x, to = c(0, 1), na.rm = TRUE)

Value

A numeric vector the same length as x, with values rescaled to lie within to[1] and to[2]. The function preserves the positions of NAs.

Arguments

x

Numeric vector. The data to be rescaled.

to

Numeric vector of length 2 giving the lower and upper limits of the target range. Defaults to c(0, 1).

na.rm

Logical. Should missing values be ignored when computing the source range? Defaults to TRUE. Any NAs in x are returned unchanged.

Details

If all non-missing values in x are identical, the function returns the midpoint of the target range (mean(to)) for those elements to avoid division by zero.

Examples

Run this code
set.seed(123)
x <- rnorm(5)

# Default 0~1 range
rescale_to_range(x)

# Rescale to -1~1
rescale_to_range(x, to = c(-1, 1))

# Preserve NAs but ignore them when determining the range
x_with_na <- c(x, NA, 10)
rescale_to_range(x_with_na, to = c(0, 100))

Run the code above in your browser using DataLab