14.3 Calculations and logical comparisons

  • R can calculate and compare things
  • Arithmetic operators
    • + - * / ^
  • Logical operators
    • & | == != > < >= <=
  • Different functions (check with ?function)
    • exp(x)=e^x log(x) log10(x) sin(x) cos(x) tan(x)
    • abs(x) sqrt(x) ceiling(x) floor(x) trunc(x) round(x, digits=n)


  • Q: How can I get help for the ceiling() function?


14.3.1 Example: Calculations and logical comparisons

# Calculations
Ergebnis <- (23+24)*11/(18+15)*5
Ergebnis
## [1] 78.33333
# Functions
log(2) # exp(1) = 2.718282^0.6931472
## [1] 0.6931472
##########################
# Comparisons.. examples #
##########################

x <- -3:3
x
## [1] -3 -2 -1  0  1  2  3
# Equals
x == 0
## [1] FALSE FALSE FALSE  TRUE FALSE FALSE FALSE
# is smaller than
x < 0
## [1]  TRUE  TRUE  TRUE FALSE FALSE FALSE FALSE
# is bigger than or equal to
x >= 0
## [1] FALSE FALSE FALSE  TRUE  TRUE  TRUE  TRUE
# unequal
x != 0
## [1]  TRUE  TRUE  TRUE FALSE  TRUE  TRUE  TRUE
# unequal(equal to 0)
!(x == 0)
## [1]  TRUE  TRUE  TRUE FALSE  TRUE  TRUE  TRUE
# bigger than -1 and smaller than 1
x > -1 & x < 1
## [1] FALSE FALSE FALSE  TRUE FALSE FALSE FALSE
# bigger than 1 and smaller than -1
x > 1 & x < -1
## [1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE
# bigger than 1 or smaller than -1
x > 1 | x < -1
## [1]  TRUE  TRUE FALSE FALSE FALSE  TRUE  TRUE


14.3.2 Exercise: Calculations and logical comparisons (Homework)

  1. Use your r-script and save the code you are using.
  2. Calculate the following terms using R.
    1. \(((3 + 4 - 5) - 9)^{2}\)
    2. \(\frac{-99}{33} + 42\)
    3. \(log(1)\)
    4. \((\sqrt{2})^{2}\)
  3. Check the following terms:
    1. \(5 = 7\)
    2. \(5 \times 5 \geq 6 \times 4\)
    3. \(\sqrt{3} \neq cos(17)\)
  4. In the mean() function it is possible to use and additional argument called trim. Find out what this argument does by checking the help file of the mean() function and write it into your script.


14.3.3 Solution: Calculations and logical comparisons