Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

R log() Function - Calculating Logarithms

R log() Function - Calculating Logarithms

R Language Examples R Language Examples

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:

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

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

)

print

(

"Original income:"

)

print

(

income

)

print

(

"After log transformation:"

)

print

(

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 R Language Examples