6  R as a Calculator

R functions as a calculator, and it has both operators (like + and -) and functions to do math (like sqrt() and log()).

5 + 2 # addition
## [1] 7
5 - 2 # subtraction
## [1] 3
5 * 2 # multiplication
## [1] 10
5 / 2 # division
## [1] 2.5
5 ^ 2 # exponentiation
## [1] 25
5 %/% 2 # integer division
## [1] 2
5 %% 2 # modulo (remainder after integer division)
## [1] 1
abs(-5) # absolute value
## [1] 5
sqrt(5) # square root
## [1] 2.236068
exp(5) # exponential function, e to the power of some number
## [1] 148.4132
log(5) # natural log (base e)
## [1] 1.609438
log(5, base = 10) # common log (base 10)
## [1] 0.69897

More complex operations can be performed by using multiple mathematical operators and parentheses. For example, convert a log odds of 1.3 into a probability following the formula \(probability = \frac{odds}{odds + 1}\):

exp(1.3) / (exp(1.3) + 1)
[1] 0.785835

Objects can be used in calculations too. Here we assign the value 1.3 to log_odds and then use it in a generic formula to get the probability:

log_odds <- 1.3
exp(log_odds) / (exp(log_odds) + 1)
[1] 0.785835

When we perform a calculation in R (or any other operation, such as loading datasets or fitting models), results are stored in the intermediate object .Last.value. We can access .Last.value to perform multi-step calculations. We can calculate the standard error of the mpg column in the mtcars dataset as the standard deviation divided by the square root of the sample size (n):

n <- length(mtcars$mpg) # number of observations
sd(mtcars$mpg) # standard deviation
[1] 6.026948
.Last.value / sqrt(n) # standard error
[1] 1.065424

These examples of R’s utility as a calculator have all used individual numbers, also called scalars, but R is not limited to such. These operations become more useful when we begin to work with numeric vectors and columns in dataframes.

6.1 Exercises

  1. Create an object, x, that is equal to \(2 ^ 5\).

  2. Create another object, y, that is the square root of x.

  3. Create another object, z, that is the absolute difference of x and y.