Arithmetic
R can be used as a calculator to perform simple mathematical operations.Math Operators
- " + " is used for addition.
- " - " is used for subtraction.
- " * " is used for multiplication.
- " / " is used for division.
- " ^ " is used for exponents. For example: $4^5 = 1024$.
Click the Run button to evaluate these math expressions.
# no pec
4 + 5
5 - 4
4 * 5
5 / 4
4^5
- " () " - Parentheses
Example:
$4(5+1) = 24$ and
$4*(5+1) = 24$ are mathematically equivalent but will return different results when inputted into R.
$4(5+1) = 24$ and
$4*(5+1) = 24$ are mathematically equivalent but will return different results when inputted into R.
# no pec
4 * (5 + 1) # Note how this line runs fine.
4(5 + 1) # This line does not run and provides an error.
Example: $\dfrac{2(5+1)^2}{4*3} = 6$
This expression can be evaluated in R:
This expression can be evaluated in R:
# no pec
2 * (5 + 1)^2 / (4 * 3)
Math Functions
- "sqrt()" is used to find the square root of a number. For example: $\sqrt{16} = 4$.
- "exp()" is used with the irrational number $e$. It raises the number $e$ to whatever power is specified in the parentheses. For example: $e^2 = 7.389056$.
- "log()" is used to take the natural log of numbers. So this is in fact $ln$, and not $log_{10}$. For example: $ln(10) = log_{e}10 = 2.302585$
- To further "prove" that R uses the natural log, this expression is evaluated below: $ln(e^1) = log_{e}e^1 = 1$.
- To use $log_{10}$ or another base, the base argument can be added inside the log() function. For example: $log_{5}25 = 2$.
Click the Run button to evaluate these math functions.
# no pec
sqrt(16)
exp(2)
log(10)
# Showing that R does use the natural log
log(exp(1))
# Showing how you can use a different base
log(25, base = 5)
$\pi$ and Trigonometry
The number $\pi$ is already stored in R as pi.
Click the Run button to evaluate these math expressions.
The trigonometric functions of sine, cosine and tangent are also in R, as sin(), cos(), and tan(), respectively. Angle inputs are to be in radians, not degrees.
# no pec
pi
2 * pi
pi / 2
Click the Run button to evaluate these math functions.
# no pec
sin(pi / 2)
cos(2 * pi)
cos(pi)
tan(pi / 4)