R Tutorial R Charts & Graphs R Statistics R References

R - abs() Function



The R abs() function returns the absolute value (positive value) of the specified number. In special cases it returns the following:

  • If the argument is infinite, the result is positive infinity.
  • If the argument is NaN, the result is NaN.

Syntax

abs(x)

Parameters

x Required. Specify column to compute on.

Return Value

Returns the absolute value (positive value) of the argument.

Example:

The example below shows the usage of abs() function.

#operating on single element atomic vector
print(abs(-10.3))
print(abs(-10.5))
print(abs(8.5))

cat("\nOperating on vector\n")
#operating on vector
v <- c(-4.1, 5.1, -6.1)
print(abs(v))

cat("\nOperating on matrix\n")
#operating on matrix
m <- matrix(c(-1.5, 2.5, -3.5, 4.5, -5.5, NaN), nrow=2)
print(abs(m))

cat("\nOperating on first column of matrix\n")
#operating on first column of matrix
print(abs(m[,1]))

The output of the above code will be:

[1] 10.3
[1] 10.5
[1] 8.5

Operating on vector
[1] 4.1 5.1 6.1

Operating on matrix
     [,1] [,2] [,3]
[1,]  1.5  3.5  5.5
[2,]  2.5  4.5  NaN

Operating on first column of matrix
[1] 1.5 2.5

❮ R Math Functions

5