The ln() function in R

If you are looking for a function to calculate the natural logarithm of a number, do not miss this article. Today, we will introduce you to the ln() function in R to find the value of the natural logarithm.

Natural logarithm

Natural logarithm of a number  x: ln(x)  is the logarithm with base  e (e = 2.7182…) .

If  ln(x) = a  we can calculate  x = e^a  where  e^a  is the exponential function.

The natural logarithm function is defined as:

 ln(x) = \int\limits_{1}^{x} \frac{dt}{t} for x > 0

The ln() function

The ln() function in R calculates the value of the natural logarithm or the logarithm base e of a number.

Syntax:

ln(x)

Parameter:

• x: A number or a vector of numbers

Some examples of the ln() function

Calculate the natural logarithm of an integer

First, we will take an example of using the ln() function to calculate the natural logarithm of an integer.

Code:

# Import required library
library("SciViews")

# Declare an integer
myInt <- 3

cat("Natural logarithm of", myInt, "is:", ln(myInt))

Result:

 Natural logarithm of 3 is: 1.098612

Calculate the natural logarithm of a float

We can also use the ln() function to find the value of the natural logarithm of a float.

Code:

# Import required library
library("SciViews")

# Declare a float
myFloat <- 22.6

cat("Natural logarithm of", myFloat, "is:", ln(myFloat))

Result:

 Natural logarithm of 22.6 is: 3.11795

Calculate the natural logarithm of a vector

There is no problem if you apply the ln() function to a vector of numbers. Let’s see the example below.

Code:

# Import required library
library("SciViews")

# Declare a vector of numbers
v <- c(1, 4.2, 2.6, 7, 2)

cat("Natural logarithm of the vector are", ln(v))

Result:

Natural logarithms of the vector are 0 1.435085 0.9555114 1.94591 0.6931472

Equivalent function to calculate the natural logarithm

Because ln() is the logarithm base e, we can use the log() function with the base exp(1) as an alternative function. We will take an example and make a comparison.

Code:

# Import required library
library("SciViews")

# Declare an integer
x <- 3

cat("Calculate the natural logarithm by the ln() function:", ln(x))
cat("\nCalculate the natural logarithm by the log() function with base exp(1):", log(x, base = exp(1)))

Result:

Calculate the natural logarithm by the ln() function: 1.098612
Calculate the natural logarithm by the log() function with base exp(1): 1.098612

Summary

In summary, the ln() function calculates the natural logarithm of a number in R. We can apply the function to an integer, float, or vector of numbers.

Maybe you are interested:

Posted in R