In addition to the basic arithmetic operations addition
(+
), subtraction (-
), multiplication
(*
) and division (/
), R has built-in standard
mathematical functions. In the following section we take a look at some
of them. Please note that in the course of this e-learning module we
will encounter many more functions in R, we will even build user-defined
functions by our own.
Absolute value function abs()
abs(3 - 12)
## [1] 9
Square root function sqrt()
sqrt(64)
## [1] 8
Exponentiation function exp()
exp(1)
## [1] 2.718282
log function (base \(e\))
log()
log(10)
## [1] 2.302585
log base 10 function log10()
log10(1000)
## [1] 3
Generally applicable: log function (base b)
log(x, base = b)
log(81, base = 3)
## [1] 4
Mathematical constant \(\pi\)
pi
## [1] 3.141593
Trigonometric functions sine, cosine, tangent (argument in
radians) sin()
, cos()
,
tan()
sin(pi / 2)
## [1] 1
cos(pi / 2)
## [1] 6.123032e-17
tan(0)
## [1] 0
Inverse trigonometric functions arc-sine, arc-cosine,
arc-tangent asin()
, acos()
,
atan()
asin(0)
## [1] 0
acos(1)
## [1] 0
atan(pi)
## [1] 1.262627
Exercise: Check whether the cosine of 360° within the unit circle is 1!
### your code here
cos(2 * pi)
## [1] 1
Round x to n decimal places
round(x,n)
round(pi, 2)
## [1] 3.14
Floor function (rounds down)
floor()
floor(pi)
## [1] 3
Ceiling function (rounds up)
ceiling()
ceiling(pi)
## [1] 4
Advanced Exercise: Consider Earth as a ball with a radius of 6371 km and calculate the distance between two meridians at the equator, 23 degree, 50 degree and 67 degree latitude. Round your answer to 1 decimal place! Bear in mind that the trigonometric functions in R expect angles in radians!
### your code here
latitudes <- c(0, 23, 50, 67)
# 1 degree = pi/180 rad
round((2 * pi * 6371) / 360 * cos((pi / 180) * latitudes), 1)
## [1] 111.2 102.4 71.5 43.4
Citation
The E-Learning project SOGA-R was developed at the Department of Earth Sciences by Kai Hartmann, Joachim Krois and Annette Rudolph. You can reach us via mail by soga[at]zedat.fu-berlin.de.
Please cite as follow: Hartmann, K., Krois, J., Rudolph, A. (2023): Statistics and Geodata Analysis using R (SOGA-R). Department of Earth Sciences, Freie Universitaet Berlin.