diff --git a/RBeginnersExercise1.Rmd b/RBeginnersExercise1.Rmd new file mode 100644 index 0000000000000000000000000000000000000000..d24b0a4530bbfe4774f00f7a9d79f34abfc58282 --- /dev/null +++ b/RBeginnersExercise1.Rmd @@ -0,0 +1,318 @@ +--- +title: "R Beginners Exercise 1: Basic Syntax" +output: + word_document: default + html_document: + toc: true +editor_options: + chunk_output_type: console +--- + +# Introduction + +Welcome to R for Beginners Exercise 1! This notebook contains the exercises for the course as well as being a work space for you to use during the session. + +To execute a line of code, click on it and press *Ctrl + Enter*. + +To execute a chunk of code, click the green run button at the top right corner of the code chunk or highlight the entire code chunk and press *Ctrl + Enter*. + +# 1.1 Load packages + +Packages provide R with lots of interesting additional features. They can be loaded to R through two methods: + +1. Enable it in the Package Window (bottom right) by finding the required package and selecting it. + +2. Use the following command to load a package, for example the `ggplot2` package: + +```{r} +library(ggplot2) +``` + +# 1.2 Printing to console + +There are two functions which can be used to print statement(s)/output to console. + +1. `print()` - Commonly used to print simple statement or one variable to console. Does not work well with concatenation\*. + +2. `paste()` - Provides more flexibility as it can be used to print multiple variables to console. Text can be concatenated\* with variable(s). + +\*concatenate: Joining two or more variables together as one. + +```{r} +# Assigning values to variables "var1" and "var2" +var1 = 25 +var2 = 30 +print("Trying to print two variables. ") +``` + +```{r eval=FALSE} +# An error will be returned for this print statement as print() can only be used to print one variable. +print(var1, var2) +``` + +```{r} +# This paste statement will print both variables to console. +paste(var1, var2) + +# Paste statement can also be used to concatenate text with variables. +paste("Variable 1:", var1, "Variable 2:", var2) +``` + +# 1.3 Types of data + +## 1.3.1 Basic datatypes + +There are 5 basic data types in R: + +1. Numeric - Any numbers, including floating-point (decimal) numbers. + +2. Integer - Whole numbers only, declared with alphabet "L" after the whole number. + +3. Complex - Numbers which involves imaginary number (i). + +4. Logical - `TRUE` or `FALSE`. + +5. Character - A single character or a string (text/sentence), need to be in double quotation mark `" "`. + +For the following variables, assign a value of the matching datatype. + +\* Remember to put equal sign for value assignment. + +```{r} +numeric_data +integer_data +complex_data +logical_data +character_data + +paste(numeric_data, integer_data, complex_data, logical_data, character_data) +``` + +## 1.3.2 Data container + +### 1.3.2.1 Vector + +Multiple values can be stored in R using a vector. Note that all elements in a vector should have the same datatype. If there is a mix of numeric and character values in a vector, numeric variables will be stored as strings. + +Vectors are created using the command `c(var1, var2, var3)`, where `var1`, `var2`, etc. are variable names. Add your code after the equal signs to create two vectors, one to store numbers and one to store words. + +```{r} +num1 = 1 +num2 = +num3 = +numbers = +print(numbers) + +txt1 = "apple" +txt2 = +txt3 = +words = +print(words) + +mix = c(num1, num2, txt1, txt2) +print(mix) +``` + +### 1.3.2.2 Vector without specifying elements + +Sometimes it can be useful to create a vector with a specific size without explicitly declaring the variables in it. This can be done by the command below. All the elements within the vector will have a starting value of 0. + +```{r} +emptyContainer = numeric(10) +``` + +The vector created using the `numeric()` command can be used to store variables with a datatype other than numeric. Initially, the vector will have datatype `numeric`. When a variable with datatype `complex` or `character` is stored in it, the vector's datatype will change. Execute the code chunk below **line-by-line** and monitor the changes to the container's datatype in the Environment window (top right). + +\* To execute a line of code, click on it and press Ctrl + Enter. + +```{r} +emptyContainer = numeric(10) # Vector created with datatype numeric +emptyContainer[1] = 10.5 # This code will not change the datatype of the vector +emptyContainer[2] = 3L # This code will not change the datatype of the vector +emptyContainer[3] = 3+5i # Changes the vector's datatype to complex +emptyContainer[4] = "apple" # Changes the vector's datatype to character +``` + +Notice when the datatype of the vector changes from `numeric` to `complex`, the format of all elements in the vector are changed to accommodate a complex number. When the datatype of the vector changes to datatype `character`, a double quotation mark is added to each element to signify a `character` type element. + +### 1.3.2.3 Table + +A data container can also store values in a table-like format. To create a table, combine two or more vectors using the function `data.frame()` . Each vector will become a column in the table (data-frame). Create a table by combining the vectors, `numbers` and `words`. + +```{r} +words_table = +print(words_table) +``` + +After executing all the code above, variables can be viewed in the Environment window (top right). If you hover your cursor on a variable, the datatype and the byte size of the variable will be shown. + +# 1.4 Operators + +## 1.4.1 `[]` Operator + +A variable within a data container can be accessed with its index by the `[]` operator. Note that the index in R starts from 1 and not 0. Complete the print statement below to print the second variable in the `mix` container. + +```{r} +print() +``` + +It is also possible to access multiple variables in a data container at once. Complete the print statement below to print the first three variables in the `mix` container. + +\* Use the `:` sign between two indexes in the `[]` operator to represents "to". Both the index stated in the square bracket are inclusive. + +```{r} +print() +``` + +Through the index, assign 1 to the 2nd, 3rd, and 4th elements in the `emptyContainer`. + +```{r} + +``` + +Now, try printing the following of the `words_table`. + +\* Use comma (`,`) to separate the row and column index, e.g., `a_random_table(row_index, column_index`. + +```{r} +# The element at the second row and first column +print() + +# The second row +print() + +# The first column +print() + +# The last two rows +print() +``` + +Other than specifying the index of a container, the `[]` operator can also be used to specify condition(s) to choose specific elements in the container. + +```{r} +print(numbers[numbers > 1]) +``` + +Try using the `[]` operator to print all the elements in the `words` container except for "apple". + +\* Use `!=` which stands for not equivalent. + +```{r} +print() +``` + +## 1.4.1 Arithmetic operators + +Arithmetic operators are mathematical notations that can be used for calculations. The basic operators are: + +- `+` Addition + +- `-` Subtraction + +- `*` Multiplication + +- `/` Division + +- `^` Exponent + +- `%%` Modulus (Division's Remainder), e.g., `4 %% 2 = 0` + +Use the requested arithmetic operators to produce the output required. + +```{r} +# Addition: Create a variable named "ans" which equals to 1 plus 2. Then print "1 plus 2 equals" followed by the value of "ans" to the console. +ans = + +# Subtraction: Create a variable named "ans" which equals to 10 minus 2. Then print "10 minus 2 equals" followed by the value of "ans" to the console. +ans = + +# Multiplication: Create a variable named "ans" which equals to 2 times 4. Then print "2 times 4 equals" followed by the value of "ans" to the console. +ans = + +# Division: Create a variable named "ans" which equals to 15 divided by 3. Then print "15 divided by 3 equals" followed by the value of "ans" to the console. +ans = + +# Exponential: Create a variable named "ans" which equals to 3 to the power of 2. Then print "3 to the power of 2 equals" followed by the value of "ans" to the console. +ans = + +# Modulus: Create a variable named "ans" which equals to the remainder of 10 divided by 3. Then print "Remainder of 10 divided by 3 equals" followed by the value of "ans" to the console. +ans = + +``` + +When doing calculations in R, you can either put your calculations in the source window/code chunk (top left), or in the console window (bottom left). Try using both for the following calculations: + +```{r} +450 / 25 +9.8 * 35 +(5*4) / 2 +``` + +## 1.4.2 Relational operators + +The basic relational operators are: + +- `==` Equivalent + +- `!=` Not equivalent + +- `>` Greater than + +- `<` Smaller than + +- `>=` Greater than or equals to + +- `<=` Smaller than or equals to + +Complete the statements below with the requested operator so all the statements will return `TRUE`. + +```{r} +test = 10 + +# equivalent +test + +# not equivalent +test + +# greater than +test + +# lesser than +test + +# greater or equals to +test + +# lesser or equals to +test + +``` + +## 1.4.3 Logical operators + +There are three basic types of logical operators: + +1. `&` - AND (`TRUE` when all conditions are satisfied) + +2. `|` - OR (`TRUE` when at least one of the conditions is satisfied) + +3. `!` - NOT (`TRUE` when the condition is not satisfied) + +Write code to represent the situations described, using a logical operator of your choice. + +\* Remember to use `==` which stands for 'is equivalent to' + +```{r} +# 10 is divisible by both 5 and 2 + + +# num is either 1 or 5 +num = 5 + + +# num is not 10 + + +```