R log() Function - Calculating Logarithms
The R log() function is used to compute the logarithm of a number.
A logarithm is the inverse of exponentiation. Logarithms are widely used in data transformation, information theory, and statistical modeling to compress the range of values.
The syntax of the log() function is as follows:
log(x, base = exp(1))
Parameter Description:
-
x Input a number or a numeric vector, which must be greater than 0.
-
base The base of the logarithm, default exp(1), the natural logarithm (base e).
Example
Natural logarithm (base e)
(
log
(
10
)
)
(
log
(
exp
(
1
)
)
)
ln(e) = 1
Logarithm with a specified base
(
log
(
100
, base
=
10
)
)
log10(100) = 2
(
log
(
8
, base
=
2
)
)
log2(8) = 3
Convenience functions
(
log10
(
1000
)
)
base 10
(
log2
(
16
)
)
base 2
The output of the code above is:
[1] 2.302585
[1] 1
[1] 2
[1] 3
[1] 3
[1] 4
Logarithmic transformation is often used to handle skewed data:
Example
Create skewed data
income
<-
c
(
5000
,
8000
,
12000
,
20000
,
50000
,
100000
,
250000
,
500000
)
Take the natural logarithm of income
log_income
<-
log
(
income
)
(
"Original income:"
)
(
income
)
(
"After log transformation:"
)
(
round
(
log_income,
2
)
)
The output of the code above is:
[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.12
R Language Examples