In programming, variables are containers in which we store data values and store the results of calculations or operations on existing data.[1]
Assignment operators allow you to place values into variables.
Assignment Operators
There are three assignment operators in R: <-, -> and =.
Performing Operations with Variables}
The <- assignment operator can also be used to perform arithmetical calculations:
# Define two variables, x and yx <-10y <-3# Perform some arithmetic operations on those variablessum <- x + ydifference <- x - yproduct <- x * y # the product is the outcome when we multiplyquotient <- x / y # the quotient is the outcome when we divide# Print results to the consoleprint(sum)
[1] 13
print(difference)
[1] 7
print(product)
[1] 30
print(quotient)
[1] 3.333333
Updating Variables
The <- operator can also be used to update variables, for example to increment a variable:
turn <-0# set 'turn' to zeroturn <- turn +1# increment 'turn' by 1print(turn) # print updated value of 'turn'
[1] 1
Data Types in R
When dealing with sport data, we are often faced with different types of data. Some data might be numerical, like a match outcome.[2] Some might be text, like a team name.[3]
In R, you can use the function to get a quick overview of the different types of data in your dataset.
There are six basic types of data that R recognises. By clearly defining which type of data each variable holds, you will find it much easier to work with the data later on.
Character
Character data types are used to represent text data, including individual characters, strings, and words. They are always enclosed in double or single quotes. Examples include “hello”, ‘R programming’.
Vectors and Basic Vector Operations
Creating Vectors
We can use the function to create a vector by combining elements. Remember, all elements in a vector have to be of the same :
# create a numeric vector with five elementsnumeric_vector <-c(1, 2, 3, 4, 5) # create a character vector with three elementscharacter_vector <-c("playerOne", "playerTwo", "playerThree")# create a logical vector with three elementslogical_vector <-c(TRUE, FALSE, TRUE)
We can perform element-wise arithmetic and logical operations on vectors:
%—————————————————————–
Finally, we can use logical to filter or subset vectors: