Skip to contents

A class and utility methods for numeric values with units

Usage

measure(x = double(), units = attr(x, "units"))

# S4 method for class 'measure'
units(x)

# S4 method for class 'measure'
units(x) <- value

Arguments

x

a numeric vector, or a measure, difftime, lubridate::duration, lubridate::interval, or lubridate::period object

units, value

a character value. See Details

Value

An object of class measure

Methods

If x is a lubridate Duration, Interval or Period object, it will be converted to difftime before running the default method.

If x is already a measure convert_units() will be called.

Units

Units are specified in the following format:

"multiplier prefix1|unit1^exponent1 prefix2|unit2^exponent2 ...".

The multiplier, prefixes and exponents are optional. For example, measure(x, "10 c|m^2 s^-1") will add units of ten centimeters per second, and measure(x, "m") simply of meters. Prefixes can be any of the SI prefixes:

Q, R, Y, Z, E, P, T, G, M, k, h, da, d, c, m, µ, (or micro), n, p, f, a, z, y, r, or q.

Units have no restriction, although difftime units are converted to s, min, hour, day and week.

Examples

(speed <- measure(1:5, "m s^-1"))
#> <measure[5]>
#> [1] 1 m s^-1 2 m s^-1 3 m s^-1 4 m s^-1 5 m s^-1
(time <- measure(50, "min"))
#> <measure[1]>
#> [1] 50 min
as.difftime(time)
#> Time difference of 50 mins
(distance <- speed * time)
#> <measure[5]>
#> [1]  50 m s^-1 min 100 m s^-1 min 150 m s^-1 min 200 m s^-1 min 250 m s^-1 min
units(distance)
#> m s^-1 min 
(distance <- measure(distance, "k|m"))
#> <measure[5]>
#> [1]  3 km  6 km  9 km 12 km 15 km

distance[2:3] <- measure(200, "m")
distance^2
#> <measure[5]>
#> [1]   9.00 km^2   0.04 km^2   0.04 km^2 144.00 km^2 225.00 km^2
mean(distance)
#> <measure[1]>
#> [1] 6.08 km

units(distance) <- "kilometers"
range(distance)
#> <measure[2]>
#> [1]  0.2 kilometers 15.0 kilometers
as.numeric(distance)
#> [1]  3.0  0.2  0.2 12.0 15.0

units(distance) <- NULL
distance
#> <measure[5]>
#> [1]  3.0  0.2  0.2 12.0 15.0
log(distance)
#> <measure[5]>
#> [1]  1.098612 -1.609438 -1.609438  2.484907  2.708050