⇦ Back

Arithmetic

All the usual mathematical operations can be done in R:

# Addition and subtraction
a <- 4 + 5 - 2
# Multiplication and division
b <- 2 * 100 / 4
# Integer division
c <- 47 %/% 5
# Exponent
d <- 2 ^ 4
# Modulus
e <- 5 %% 13

# Output to console
c(a, b, c, d, e)
## [1]  7 50  9 16  5

For more complicated operations there are functions to do it for you:

# Square root
a <- sqrt(49)
# Round down
b <- floor(-6.28318531)
# Round up
c <- ceiling(-6.28318531)
# Round towards zero
d <- trunc(-6.28318531)
# Round to a certain number of decimal places
e <- round(-6.28318531, 3)
# Round to a certain number of significant figures
f <- signif(-6.28318531, 3)

# Output to console
c(a, b, c, d, e, f)
## [1]  7.000 -7.000 -6.000 -6.000 -6.283 -6.280
# Remove trailing zeros
# Note that this converts the number to a string
g <- prettyNum(-6.28000, zero.print = NULL)
g
## [1] "-6.28"

Equality

If you want to test if something is equal to a particular number, you can use two equal signs: ==

# Is 2 + 2 equal to 4?
2 + 2 == 4
## [1] TRUE

As you can see, the word TRUE has been returned in response to the statement that 2 + 2 is equal to 4. This value TRUE is an example of a Boolean: something that is either true or false. If we instead make an incorrect statement then the Boolean that is returned has the opposite value: FALSE

# Is 2 + 2 equal to 5?
2 + 2 == 5
## [1] FALSE

See more about Booleans on this page.

Remember that a single equals sign = is used for assignment - setting the value of a variable equal to something - whereas the double equals sign == is used for testing equality:

# Is a equal to b?
a = 2 + 2
b = 4
a == b
## [1] TRUE

Inequality

If we instead want to test if something is not equal to a particular number we can use !=

# Is 2 + 2 not equal to 5?
2 + 2 != 5
## [1] TRUE

In programming, the exclamation mark often means “not”. So != means “not equal to”.

Similarly, the ‘greater than’, ‘less than’, ‘greater than or equal to’ and ‘less than or equal to’ tests can be applied using the operators >, <, >= and <=, respectively:

a = 2 > 1
b = 1 < 2
c = 1 >= 1
d = 1 <= 1
c(a, b, c, d)
## [1] TRUE TRUE TRUE TRUE

These operators can be applied to an entire vector of numbers at once. This means, for example, that we can find out which numbers in a list are greater than 5:

# Which of these numbers are greater than 5?
x = c(1, 2, 3, 4, 5, 6, 7, 8)
x > 5
## [1] FALSE FALSE FALSE FALSE FALSE  TRUE  TRUE  TRUE

If you prefer 1s and 0s to trues and falses, you can convert Booleans to numbers using the as.integer() function:

# Which of these numbers are greater than 5?
x = c(1, 2, 3, 4, 5, 6, 7, 8)
as.integer(x > 5)
## [1] 0 0 0 0 0 1 1 1

⇦ Back