R can be used to perform arithmetic operations.
To run a command in a basic R script and in R Markdown, you can place your cursor at the end of the code line and hit COMMAND + ENTER (Mac) or CTRL + ENTER (Windows), or select the line and click on the icon RUN at the top right of the text editor.
# Addition
1 + 2
## [1] 3
# Subtraction
1 - 2
## [1] -1
# Division
1 / 2
## [1] 0.5
# Multiplication
2 * 2
## [1] 4
# Exponentiation
2^2
## [1] 4
The R language is based on the concept of object. Objects are the building blocks of all operations in R. Objects are used to store data and perform operations on data.
# Assign a numeric value, called a scalar, to an object named "a"
a <- 2
a
## [1] 2
b <- 3
# Perform arithmetic operations with objects
a + b
## [1] 5
# Assign non-numeric values to objects using quotes
a <- "a" # Note that this overwrites the previous object with the same name
a
## [1] "a"
my_name <- "Sarah"
my_name
## [1] "Sarah"
Assign two scalars to objects and perform an arithmetic operation on these objects, such that the result is 9. Add a comment to describe what the code is doing.
There are different types of object in R. A scalar contains a single element, and vectors and matrices contain multiple elements. Scalars can be combined into vectors, and vectors can be combined into matrices.
Source, with modification: https://rpubs.com/evelynebrie/introductionR
Scalars, vectors and matrices can have different classes. There are three main classes of objects for our purposes: character, numeric and logical.
# Use the in-built function "class" to find the class of an object
class(b)
## [1] "numeric"
class(my_name)
## [1] "character"
# Create a logical object
c <- TRUE # This creates a logical scalar named "c" with the value "TRUE"
d <- FALSE
class(c)
## [1] "logical"
class(d)
## [1] "logical"
You will encounter logical language when using logical operators.
# Equality
b == 2 # Does b equal 2?
## [1] FALSE
# Inequality
b < 3 # Is b smaller than 3?
## [1] FALSE
b > 3 # Is b greater than 3?
## [1] FALSE
b >= 3 # Is b greater or equal than 3?
## [1] TRUE
b != 2 # ! is used as "not"; in this case, "not equal"
## [1] TRUE
# OR, AND
e <- 2
b | e == 2 # use | for OR
## [1] TRUE
b & e == 2 # use & for AND
## [1] TRUE
Assign two scalars to objects and perform a logical operation with these objects such that the result is “TRUE”.
We can store data in a matrix by creating vectors and binding them. For instance, we would like to store the data for a meal plan in a matrix, as below. Each row is a different day of the week. The vectors contain data on the day of the week, the protein, the vegetable, the drink, and the dessert for the lunch on that day.
Inspired by: https://rpubs.com/evelynebrie/introductionR
# Create the vectors of data
day <- c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")
protein <- c("Kebab", "Steak", "Prawn", "Lamb", "Octopus")
veggie <- c("Tomato", "Carrot", "Avocado", "Asparagus", "Beet")
drink <- c("Coffee pot", "Coffe cup", "Tea", "Water", "Beer")
dessert <- c("Ice cream", "Cupcake", "Durian", "Doughnut", "Birthday cake")
# Bind the vectors
meal_plan <- cbind(day, protein, veggie, drink, dessert) # cbind() performs a column bind
meal_plan
## day protein veggie drink dessert
## [1,] "Monday" "Kebab" "Tomato" "Coffee pot" "Ice cream"
## [2,] "Tuesday" "Steak" "Carrot" "Coffe cup" "Cupcake"
## [3,] "Wednesday" "Prawn" "Avocado" "Tea" "Durian"
## [4,] "Thursday" "Lamb" "Asparagus" "Water" "Doughnut"
## [5,] "Friday" "Octopus" "Beet" "Beer" "Birthday cake"
Let’s say someone else has created the meal plan for us, and we would like to know what dessert we will eat on the first day of the week. We can get the answer by using indexing—to refer to the row and column position of the element—and subsetting by using the element’s index to return the desired value.
Inspired by: https://rpubs.com/evelynebrie/introductionR
To subset a vector or matrix we use brackets. We indicate the index of the element with number(s) inside the brackets. For a vector, which is one-dimensional, only one index position is needed. For a matrix, which has two dimensions, we enter the row position first, followed by a comma and the column position.
# Find the dessert on the first day by subsetting a matrix
meal_plan[1,5] # the first index position tells R to look in the first row, and the second index position tells R to look in the fifth column
## dessert
## "Ice cream"
meal_plan[1,"dessert"] # you can also use column names
## dessert
## "Ice cream"
# Find the dessert on the first day by subsetting a vector
dessert[1]
## [1] "Ice cream"
Find what beverage you will drink on Thursday by using subsetting.
We can also use logical operators instead of indexing to subset data. When using logical operators on multidimensional objects, like vectors and matrices, the evaluation is done element-wise. Remember, R is case-sensitive.
# Find on which day you will eat steak:
# 1. Create a vector with the logical values for each day
eat_steak <- meal_plan[, "protein"] == "Steak" # evaluates each element in "protein" (row position is empty) and returns a logical value. Remember, each element of protein represents a different day.
# 2. Subset the day for which the evaluation returned "TRUE"
meal_plan[eat_steak, "day"] # Instead of an index, which we don't know, we used the logical values that R returned
## day
## "Tuesday"
# Find if crab is part of your meal plan using the "element of" operator
"Crab" %in% meal_plan
## [1] FALSE
"Crab" %in% protein
## [1] FALSE
# Find if tofu and tempeh are part of your meal plan by using a vector
vegan <- c("Tofu", "Tempeh")
vegan %in% protein # The evaluation is done element-wise with respect to the first object
## [1] FALSE FALSE
# Find if milk is NOT part of your meal plan
!("Milk" %in% meal_plan)
## [1] TRUE
Functions are used to perform operations on objects. Functions have arguments that are enclosed in parentheses, one of which is the object on which to perform the operation.
# Count
length(day) # Number of elements in a vector
## [1] 5
nrow(meal_plan) # Number of rows in a matrix
## [1] 5
ncol(meal_plan) # Number of columns in a matrix
## [1] 5
# Sort
sort(protein) # Sorts in alphabetical order
## [1] "Kebab" "Lamb" "Octopus" "Prawn" "Steak"
numbers <- c(3,5,2,1,3)
sort(numbers) # Sorts in ascending order
## [1] 1 2 3 3 5
sort(x = numbers, decreasing = TRUE) # Sorts in descending order
## [1] 5 3 3 2 1
# Unique values
unique(numbers)
## [1] 3 5 2 1
Count the number of unique values in the protein vector.
You can also use logical operators with functions to perform operations on a subset of data.
# Count how many numbers are greater than 2 in the numbers vector using the "which" logical operator
which(numbers > 2 ) # Returns a vector with the positions of the elements in the numbers vector that evaluate as "TRUE"
## [1] 1 2 5
length(which(numbers >2 )) # Counting how many elements are "TRUE"
## [1] 3
# You can also break your code in multiple lines/steps if that helps
index <- which(numbers > 2 ) # Create an object with the indices of the elements that evaluate as "TRUE"
length(index)
## [1] 3
This work by Sarah Lachance is licensed under CC BY-NC-ND 4.0