R Tutorial R Charts & Graphs R Statistics R References

R - log() Function



The R log() function returns the natural logarithm (base e) or logarithm to the specified base 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

log(x, base)

Parameters

x Required. Specify column to compute on.
base Optional. Specify the base. Default is e.

Return Value

Returns the natural logarithm or logarithm to the specified base of a given number.

Example:

In the example below, log() function is used to calculate the natural logarithm of a given number.

#operating on single element atomic vector
print(log(0))
print(log(1))
print(log(3))

cat("\nOperating on vector\n")
#operating on vector
v <- c(5, 10, 50)
print(log(v))

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

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

The output of the above code will be:

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

Operating on vector
[1] 1.609438 2.302585 3.912023

Operating on matrix
         [,1]     [,2]     [,3]
[1,] 0.000000 3.912023 6.214608
[2,] 2.302585 4.605170      NaN

Operating on first column of matrix
[1] 0.000000 2.302585

Example:

Consider one more example where different base is used to compute the logarithms.

#operating on single element atomic vector
print(log(10, 2))
print(log(10, 5))
print(log(10, 10))

cat("\nOperating on vector\n")
#operating on vector
v <- c(10, 50, 100)
#using base-10
print(log(v, 10))
#using base as vector
print(log(v, c(10, 50, 100)))

The output of the above code will be:

[1] 3.321928
[1] 1.430677
[1] 1

Operating on vector
[1] 1.00000 1.69897 2.00000
[1] 1 1 1

❮ R Math Functions