R Programming abs syntax
abs(x)
In R, abs returns the magnitude of a number. For example, the absolute value of −6 is 6, and the absolute value of 0 is 0.
abs
cat(abs(-3), "\n", sep = "")
3
abs(x)
| Input | A numeric or complex vector. |
|---|---|
| Result | One magnitude per element. For a complex value this is its modulus. Missing values propagate. |
A shop records a surplus as a positive count and a shortage as a negative count. The reconciliation report asks how many items differ in each case, regardless of direction.
# Positive integer value
n <- abs(9)
cat("The absolute value of 9 is", n, "\n", sep = " ")
# Negative integer value
x <- abs(-6)
cat("The absolute value of -6 is", x, "\n", sep = " ")
The absolute value of 9 is 9 The absolute value of -6 is 6
A scale reports deviations on either side of its reference weight. Find the size of each deviation while keeping the fractional part so small differences remain visible.
# Positive floating point value
n <- abs(9.3)
cat("The absolute value of 9.3 is", n, "\n", sep = " ")
# Negative floating point value
x <- abs(-6.3)
cat("The absolute value of -6.3 is", x, "\n", sep = " ")
The absolute value of 9.3 is 9.3 The absolute value of -6.3 is 6.3
A sensor can use infinity to mark a reading outside its measuring range. Pass both signs through this operation so the display can handle the result or the reported error deliberately.
# Positive ∞ infinite value
n <- abs(Inf)
cat("The absolute value of Inf is", n, "\n", sep = " ")
# Negative ∞ infinite value
x <- abs(-Inf)
cat("The absolute value of -Inf is", x, "\n", sep = " ")
The absolute value of Inf is Inf The absolute value of -Inf is Inf
A stocktake compares what the scanner found with what the inventory system expected. The report needs to distinguish a shortage, a surplus and an exact match before deciding whether to investigate.
scanned <- 47
expected <- 52
cat(abs(scanned - expected), "\n", sep = "")
5
The scanner found 47 items against 52 on the manifest. The discrepancy is five items. Keep the signed difference separately to distinguish a shortage from a surplus.
A school library expects 48 loan chargers on its shelf after class. A student counts 45. The handover form has a separate field for the size of the discrepancy, whether the shelf is short or over.
expected <- 48
counted <- 45
cat(abs(counted - expected), "chargers")
3 chargers
The signed difference is minus three. Its magnitude gives the three chargers the next shift needs to account for.
A class logs the courtyard temperature at sunrise and again before lunch. The report asks how far apart the readings are, even when one is below freezing.
The two readings sit seven one-degree intervals apart on the same scale.
sunrise <- -3
midday <- 4
cat(abs(midday - sunrise), "°C\n")
7 °C
Reference: R numeric operations