7 R as a Calculator

R functions as a calculator.

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
log(5) # natural log
[1] 1.609438

More complex operations can be performed by using multiple mathematical operators and parentheses:

abs(5 - sqrt(2) * (5 ^ (5/2) - 2))
[1] 71.22851

Objects can be uses in calculations, too. Here we assign the value 5 to x and then add 2 to it.

x <- 5
x + 2
[1] 7

Note that x retains its original value of 5 since we did not reassign the result to x.

x
[1] 5

To update x with the result of x + 2, assign it to x:

x <- x + 2
x
[1] 7

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 (sd) 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. These operations become more useful when we begin to work with numeric vectors and columns in dataframes.

7.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.