R log() Function - Calculate Logarithms
The R log() function is used to calculate the logarithm of numeric values.
A logarithm is the inverse operation of exponentiation. Logarithms are widely used in data transformation, information theory, and statistical modeling to compress the range of numeric values.
The syntax of the log() function is as follows:
log(x, base = exp(1))
Parameter description:
xInput numeric value or numeric vector, must be greater than 0.
baseThe base of the logarithm, defaults to exp(1), i.e., the natural logarithm (base e).
Example
# Natural logarithm (base e)
print(log(10))
print(log(exp(1))) # ln(e) = 1
# Logarithm with a specified base
print(log(100, base = 10)) # log10(100) = 2
print(log(8, base = 2)) # log2(8) = 3
# Convenience functions
print(log10(1000)) # Base 10
print(log2(16)) # Base 2
print(log(10))
print(log(exp(1))) # ln(e) = 1
# Logarithm with a specified base
print(log(100, base = 10)) # log10(100) = 2
print(log(8, base = 2)) # log2(8) = 3
# Convenience functions
print(log10(1000)) # Base 10
print(log2(16)) # Base 2
Executing the above code produces the following output:
[1] 2.302585 [1] 1 [1] 2 [1] 3 [1] 3 [1] 4
Logarithmic transformation is often used to handle skewed distribution data:
Example
# Create data with skewness
income <- c(5000, 8000, 12000, 20000, 50000, 100000, 250000, 500000)
# Take the natural logarithm of income
log_income <- log(income)
print("Original income:")
print(income)
print("After logarithmic transformation:")
print(round(log_income, 2))
income <- c(5000, 8000, 12000, 20000, 50000, 100000, 250000, 500000)
# Take the natural logarithm of income
log_income <- log(income)
print("Original income:")
print(income)
print("After logarithmic transformation:")
print(round(log_income, 2))
Executing the above code produces the following output:
[1] "原始收入:" [1] 5000 8000 12000 20000 50000 100000 250000 500000 [1] "对数变换后:" [1] 8.52 8.99 9.39 9.90 10.82 11.51 12.43 13.12Other extensions
R Language Examples