R log2() Function

The log2() function is used to calculate the base-2 logarithm of a number or a vector of numbers.

Syntax

log2(number)

Parameters

number: It is a number whose logarithm base 2 must be calculated.

Return value

It returns the logarithm of a number to the base 2.

  1. If the number is zero, then this function outputs -Inf.
  2. If the number is negative, this function outputs NaN and a warning message.

Example 1: Basic usage

Usage of log2() function

log2(11)
log2(1)

Output

[1] 3.459432
[1] -Inf

Example 2: Handling Zero and Negative Values

# Logarithm of zero
log2_zero <- log2(0)
print(log2_zero) # Expected output: -Inf

# Logarithm of a negative number
log2_negative <- log2(-1)
print(log2_negative) # Expected output: NaN

Output

[1] -Inf
Warning message:
NaNs produced

[1] NaN

Example 3: Using vector

Calculating the log2() of a vector

vec <- c(1, 2, 4, 8) 

cat("The vector sequence is: ") 

cat(log2(vec), "\n")

Output

The vector sequence is: 0 1 2 3

Example 4: Plotting

Open the Rstudio and write the following code, and it will create a graph.

vec <- seq(0, 1, by = 0.1) 

plot(data, log2(vec), typ = "l", col = "red")

Output

Plotting the log2() function

That’s it!

Leave a Comment