R Tutorial R Charts & Graphs R Statistics R References

R - log2() Function



The R log2() function returns the base-2 logarithm of a given number. In special cases it returns the following:

  • If the argument is NaN or less than zero, then the result is NaN.
  • If the argument is positive infinity, then the result is positive infinity.
  • If the argument is zero, then the result is negative infinity.

Syntax

log2(x)

Parameters

x Required. Specify column to compute on.

Return Value

Returns the base-2 logarithm of the value.

Example:

In the example below, log2() function is used to calculate the base-2 logarithm of a given number.

#operating on single element atomic vector
print(log2(0))
print(log2(0.5))
print(log2(1))

cat("\nOperating on vector\n")
#operating on vector
v <- c(2, 10, 64)
print(log2(v))

cat("\nOperating on matrix\n")
#operating on matrix
m <- matrix(c(1, 2, 4, 10, 100, NaN), nrow=2)
print(log2(m))

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

The output of the above code will be:

[1] -Inf
[1] -1
[1] 0

Operating on vector
[1] 1.000000 3.321928 6.000000

Operating on matrix
     [,1]     [,2]     [,3]
[1,]    0 2.000000 6.643856
[2,]    1 3.321928      NaN

Operating on first column of matrix
[1] 0 1

❮ R Math Functions