Introduction To R Programming
Introduction To R Programming
What is R
R is a popular programming language used for statistical computing and graphical presentation.
Why Use R?
• It is a great resource for data analysis, data visualization, data science and machine
learning
• It is easy to draw graphs in R, like pie charts, histograms, box plot, scatter plot, etc++
• It has many packages (libraries of functions) that can be used to solve different problems
RStudio
Here's a breakdown of what RStudio is and why it's so widely used by R users:
RStudio's interface is typically divided into several panes, providing a well-organized workspace:
1. Source Editor: This is where you write and edit your R scripts. It includes features like:
1
o Code Folding: Allows you to collapse sections of code to improve readability.
o Running Code: You can execute selected lines of code, the entire script, or
individual functions directly from the editor.
o You can type R commands directly here and see the results immediately.
o Output from your R scripts run in the Source Editor will also appear here.
3. Environment Pane: This pane shows the objects (variables, functions, data frames, etc.)
that are currently loaded in your R session.
o It provides a clear overview of your data and allows you to inspect their structure
and contents.
o You can easily view data frames, lists, and other data structures.
4. Files, Plots, Packages, Help, Viewer Pane: This pane is multifaceted and provides access
to various resources:
o Files: A file browser to navigate your project directory and open files.
o Plots: Displays plots generated by your R code. You can zoom, export, and
navigate between plots.
o Packages: Lists the installed R packages and allows you to load and unload them.
You can also easily install new packages from here.
o Viewer: Used for displaying interactive content like HTML outputs from R
Markdown documents or Shiny applications.
Be you start learning R, you must have R and RStudio installed on your computer. Let's break
down how to get R and RStudio set up on the three major operating systems: Windows, macOS,
2
and Linux. R is the programming language itself, and RStudio is a popular integrated
development environment (IDE) that makes working with R much easier. You'll need to install R
first, and then RStudio.
The process generally involves two main steps for each operating system:
1. Install R:
o Click on "base".
o Click on the link that says "Download R 4.x.x for Windows" (the version number
will vary).
o Follow the prompts in the installation wizard. You can generally accept the
default settings. Make sure to install both the 32-bit and 64-bit versions if you're
unsure which you'll need, or just the 64-bit version if your system supports it.
o Once the installation is complete, you can open R from the Start Menu to verify
it's installed.
2. Install RStudio:
o Go to the RStudio
website: [Link]
o Click on the "DOWNLOAD" button for the free "RStudio Desktop (Open Source
License)".
3
o The website should automatically detect your operating system and provide a
download link for Windows. Click on the download link (e.g., [Link].x-
[Link]).
o Follow the prompts in the installation wizard. You can generally accept the
default settings.
o Once the installation is complete, you can open RStudio from the Start Menu.
RStudio should automatically detect your R installation.
1. Install R:
o Click on the link for the latest R version (e.g., "[Link]"). Make sure to
download the package that matches your macOS version and architecture (Intel
or Apple Silicon - M1/M2/M3 chips).
4
o Follow the prompts in the installation wizard. You can generally accept the
default settings.
o Once the installation is complete, you can find the R application in your
Applications folder.
2. Install RStudio:
o Go to the RStudio
website: [Link]
o Click on the "DOWNLOAD" button for the free "RStudio Desktop (Open Source
License)".
o The website should automatically detect your operating system and provide a
download link for macOS. Click on the download link (e.g., [Link].x-
[Link]).
o Once the copying is complete, you can open RStudio from your Applications
folder or Launchpad. RStudio should automatically detect your R installation.
Installing R and RStudio on Linux is often done through your distribution's package manager,
which is the recommended and most straightforward method. The exact commands will vary
slightly depending on your Linux distribution (e.g., Ubuntu, Debian, Fedora, CentOS).
3. Install RStudio: Download the appropriate RStudio package for your distribution and
install it.
• Ubuntu/Debian:
o Install R:
5
o Copy sudo apt update
r-base installs the core R system, and r-base-dev includes development headers and libraries
needed for installing R packages that require compilation.
o Install RStudio:
▪ Go to the RStudio
website: [Link]
▪ Click on the "DOWNLOAD" button for the free "RStudio Desktop (Open
Source License)".
• Fedora/CentOS/RHEL:
o Install R:
o Copy sudo yum update # Or sudo dnf update for newer Fedora
o Install RStudio:
▪ Go to the RStudio
website: [Link]
6
▪ Click on the "DOWNLOAD" button for the free "RStudio Desktop (Open
Source License)".
▪ Find the download link for your specific distribution version (e.g., rstudio-
[Link].x-x86_64.rpm).
• Adding CRAN Repository (Optional but Recommended): For the latest R versions and
easier updates, you can add the official CRAN repository to your package manager's
sources. The instructions for this vary depending on your distribution and are available
on the CRAN website for your specific Linux flavor. This allows you to install R directly
from CRAN's servers using your package manager.
After Installation:
• Open RStudio: Launch the RStudio application. It should automatically detect your R
installation.
• Verify Installation: In the RStudio console, type [Link] and press Enter. This
should display the installed R version. You can also try running a simple R command
like print("Hello, R!").
When you have downloaded and installed R, you can run R on your computer.
The screenshot below shows how it may look like when you run R on a Windows PC:
7
If you type 5 + 5, and press enter, you will see that R outputs 10.
R Syntax
Syntax
Example: type the following lines in your R environment and run it as a script
"Hello World!"
"Introduction to R Programming"
Output:
8
[1] "Introduction to R Programming"
Example:
456
500
Output:
[1] 456
[1] 500
Output: [1] 10
Example:
a <- 67
b <- 53
a+b
Print
Unlike many other programming languages, you can output code in R without using a print
function:
Example
"Hello World!"
However, R does have a print() function available if you want to use it. This might be useful if
you are familiar with other programming languages, such as Python, which often uses
the print() function to output code.
Example
print("Hello World!")
And there are times you must use the print() function to output code, for example when
working with for loops
It is up to you whether you want to use the print() function to output code. However, when your
code is inside an R expression (e.g. inside curly braces {} like in the example above), use
the print() function to output the result.
9
R Comments
Comments
Comments can be used to explain R code, and to make it more readable. It can also be used to
prevent execution when testing alternative code.
Comments starts with a #. When executing code, R will ignore anything that starts with #.
Comments do not have to be text to explain the code, it can also be used to prevent R from
executing the code.
Multiline Comments
Unlike other programming languages, such as Java, there are no syntax in R for multiline
comments. However, we can just insert a # for each line to create multiline comments:
Example
# This is a comment
# written in
# more than just one line
"Hello World!"
R Variables
Creating Variables in R
Variables are containers for storing data values.
R does not have a command for declaring a variable. A variable is created the moment you first
assign a value to it. To assign a value to a variable, use the <- sign. To output (or print) the
variable value, just type the variable name:
Example
name <- "John"
age <- 40
10
From the example above, name and age are variables, while "John" and 40 are values.
In other programming languages, it is common to use = as an assignment operator. In R, we can
use both = and <- as assignment operators.
However, <- is preferred in most cases because the = operator can be forbidden in some
contexts in R.
However, R does have a print() function available if you want to use it. This might be useful if
you are familiar with other programming languages, such as Python, which often use
a print() function to output variables.
Example
name <- "John Doe"
print(name) # print the value of the name variable
Example:
university_name <- "Novena University Ogume"
print(university_name) # print the value of the university_name variable
b <- 53
print(b) # print the value of b variable
like we stated earlier, there are times you must use the print() function to output code, for
example when working with for loops:
Example
for (x in 1:5) {
print(x)
}
output:
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
11
R Concatenate Elements
Concatenate Elements
You can also concatenate, or join, two or more elements, by using the paste() function.
To combine both text and a variable, R uses comma (,):
Example
text <- "awesome"
num1 + num2
If you try to combine a string (text) and a number, R will give you an error:
Example
num <- 5
text <- "Some text"
num + text
Result:
Error in num + text : non-numeric argument to binary operator
Multiple Variables
R allows you to assign the same value to multiple variables in one line:
Example
# Assign the same value to multiple variables in one line
var1 <- var2 <- var3 <- "Novena University"
12
Output:
[1] "Novena University"
[1] "Novena University"
[1] "Novena University"
Variable Names
A variable can have a short name (like x and y) or a more descriptive name (age, carname,
total_volume).
Rules for R variables are:
• A variable name must start with a letter and can be a combination of letters, digits,
period(.)
and underscore(_). If it starts with period(.), it cannot be followed by a digit.
• A variable name cannot start with a number or underscore (_)
• Variable names are case-sensitive (age, Age and AGE are three different variables)
• Reserved words cannot be used as variables (TRUE, FALSE, NULL, if...)
R Data Types
Data Types
In programming, data type is an important concept.
Variables can store data of different types, and different types can do different things.
In R, variables do not need to be declared with any particular type, and can even change type
after they have been set:
Example
my_var <- 30 # my_var is type of numeric
my_var <- "Sally" # my_var is now of type character (aka string)
13
R has a variety of data types and object classes. You will learn much more about these as you
continue to get to know R.
We can use the class() function to check the data type of a variable:
Example
# numeric
x <- 10.5
class(x)
# integer
x <- 1000L
class(x)
# complex
x <- 9i + 3
class(x)
# character/string
x <- "R is exciting"
class(x)
# logical/boolean
x <- TRUE
class(x)
We will learn much more about the individual data types in the coming sections.
R Numbers
Numbers
There are three number types in R:
• numeric
• integer
• complex
14
Variables of number types are created when you assign a value to them:
Example
x <- 10.5 # numeric
y <- 10L # integer
z <- 1i # complex
1. Numeric
A numeric data type is the most common type in R, and contains any number with or without a
decimal, like: 10.5, 55, 787:
Example
x <- 10.5
y <- 55
2. Integer
Integers are numeric data without decimals. This is used when you are certain that you will
never create a variable that should contain decimals. To create an integer variable, you must use
the letter L after the integer value:
Example
x <- 1000L
y <- 55L
3. Complex
A complex number is written with an "i" as the imaginary part:
Example
x <- 3+5i
y <- 5i
15
# Print values of x and y
x
y
Type Conversion
You can convert from one type to another with the following functions:
• [Link]()
• [Link]()
• [Link]()
Example
x <- 1L # integer
y <- 2 # numeric
output:
[1] 1
[1] 2.8
[1] 1
[1] 2
[1] "numeric"
[1] "integer"
R Math
16
Simple Math
In R, you can use operators to perform common mathematical operations on numbers.
The + operator is used to add together two values:
Example
10 + 5
sqrt()
The sqrt() function returns the square root of a number:
Example
sqrt(16)
output: [1] 4
abs()
The abs() function returns the absolute (positive) value of a number:
Example
abs(-4.7)
output: [1] 4.7
floor(1.4)
output: [1] 1
17
R Strings
String Literals
Strings are used for storing text.
A string is surrounded by either single quotation marks, or double quotation marks:
"hello" is the same as 'hello':
Example
"hello"
'hello'
Multiline Strings
You can assign a multiline string to a variable like this:
Example
str <- "Novena University is a private university,
located in Ogume,
in Delata State,
south-south region of Nigeria."
However, note that R will add a "\n" at the end of each line break. This is called an escape
character, and the n character indicates a new line.
If you want the line breaks to be inserted at the same position as in the code, use
the cat() function:
Example
str <- "Novena University is a private university,
located in Ogume,
in Delata State,
south-south region of Nigeria."
cat(str)
output:
Novena University is a private university,
located in Ogume,
in Delata State,
18
south-south region of Nigeria.
String Length
There are many useful string functions in R. For example, to find the number of characters in a
string, use the nchar() function:
Example
str <- "Hello World!"
Check a String
Use the grepl() function to check if a character or a sequence of characters are present in a
string:
Example
str <- "Hello World!"
grepl("H", str)
grepl("Hello", str)
grepl("X", str)
output:
[1] TRUE
[1] TRUE
[1] FALSE
paste(str1, str2)
output: [1] "Hello World"
R Escape Characters
Escape Characters
To insert characters that are illegal in a string, you must use an escape character.
An escape character is a backslash \ followed by the character you want to insert.
An example of an illegal character is a double quote inside a string that is surrounded by double
quotes:
Example
19
str <- "Novena University is one of the "private" universities in Nigeria."
str
Result:
Error: unexpected symbol in str <- "Novena University is one of the "private" universities in
Nigeria."
str
cat(str)
Note that auto-printing the str variable will print the backslash in the output. You can use
the cat() function to print it without backslash.
\\ Backslash
\n New Line
\r Carriage Return
\t Tab
\b Backspace
20
You can also compare two variables:
Example
a <- 10
b <- 9
You can also run a condition in an if statement, which you will learn much more about in
the if..else section.
Example
a <- 200
b <- 33
if (b > a) {
print ("b is greater than a")
} else {
print("b is not greater than a")
}
output:
[1] "b is not greater than a"
R Operators
Operators
Operators are used to perform operations on variables and values.
In the example below, we use the + operator to add together two values:
Example
10 + 5
R Arithmetic Operators
Arithmetic operators are used with numeric values to perform common mathematical
operations:
Operator Name Example
21
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
^ Exponent x^y
R Assignment Operators
Assignment operators are used to assign values to variables:
Example
my_var <- 3
my_var <<- 3
3 -> my_var
3 ->> my_var
Note: <<- is a global assigner. We will learn more about this in the Global Variable section.
It is also possible to turn the direction of the assignment operator.
x <- 3 is equal to 3 -> x
R Comparison Operators
Comparison operators are used to compare two values:
Operator Name Example
== Equal x == y
!= Not equal x != y
22
>= Greater than or equal to x >= y
R Logical Operators
Logical operators are used to combine conditional statements:
Operator Description
&& Logical AND operator - Returns TRUE if both statements are TRUE
R Miscellaneous Operators
Miscellaneous operators are used to manipulate data:
Operator Description Example
R If ... Else
== Equal x == y
!= Not equal x != y
23
> Greater than x>y
These conditions can be used in several ways, most commonly in "if statements" and loops.
The if Statement
An "if statement" is written with the if keyword, and it is used to specify a block of code to be
executed if a condition is TRUE:
Example
a <- 33
b <- 200
if (b > a) {
print("b is greater than a")
}
In this example we use two variables, a and b, which are used as a part of the if statement to
test whether b is greater than a. As a is 33, and b is 200, we know that 200 is greater than 33,
and so we print to screen that "b is greater than a".
R uses curly brackets { } to define the scope in the code.
Else If
The else if keyword is R's way of saying "if the previous conditions were not true, then try this
condition":
Example
a <- 33
b <- 33
if (b > a) {
print("b is greater than a")
} else if (a == b) {
print ("a and b are equal")
}
In this example a is equal to b, so the first condition is not true, but the else if condition is true,
so we print to screen that "a and b are equal".
You can use as many else if statements as you want in R.
Else
24
The else keyword catches anything which isn't caught by the preceding conditions:
Example
a <- 200
b <- 33
if (b > a) {
print("b is greater than a")
} else if (a == b) {
print("a and b are equal")
} else {
print("a is greater than b")
}
In this example, a is greater than b, so the first condition is not true, also the else if condition is
not true, so we go to the else condition and print to screen that "a is greater than b".
You can also use else without else if:
Example
a <- 200
b <- 33
if (b > a) {
print("b is greater than a")
} else {
print("b is not greater than a")
}
R Nested If
Nested If Statements
You can also have if statements inside if statements, this is called nested if statements.
Example
x <- 41
if (x > 10) {
print("Above ten")
if (x > 20) {
print("and also above 20!")
} else {
print("but not above 20.")
}
} else {
print("below 10.")
}
25
output:
[1] "Above ten"
[1] "and also above 20!"
R - AND OR Operators
AND
The & symbol (and) is a logical operator, and is used to combine conditional statements:
Example
Test if a is greater than b, AND if c is greater than a:
a <- 200
b <- 33
c <- 500
OR
The | symbol (or) is a logical operator, and is used to combine conditional statements:
Example
Test if a is greater than b, or if c is greater than a:
a <- 200
b <- 33
c <- 500
if (a > b | a > c) {
print("At least one of the conditions is true")
}
R While Loop
Loops
Loops can execute a block of code as long as a specified condition is reached.
Loops are handy because they save time, reduce errors, and they make code more readable.
R has two loop commands:
• while loops
• for loops
R While Loops
With the while loop we can execute a set of statements as long as a condition is TRUE:
26
Example
Print i as long as i is less than 6:
i <- 1
while (i < 6) {
print(i)
i <- i + 1
}
In the example above, the loop will continue to produce numbers ranging from 1 to 5. The loop
will stop at 6 because 6 < 6 is FALSE.
The while loop requires relevant variables to be ready, in this example we need to define an
indexing variable, i, which we set to 1.
Note: remember to increment i, or else the loop will continue forever.
Break
With the break statement, we can stop the loop even if the while condition is TRUE:
Example
Exit the loop if i is equal to 4.
i <- 1
while (i < 6) {
print(i)
i <- i + 1
if (i == 4) {
break
}
}
The loop will stop at 3 because we have chosen to finish the loop by using the break statement
when i is equal to 4 (i == 4).
Next
With the next statement, we can skip an iteration without terminating the loop:
Example
Skip the value of 3:
i <- 0
while (i < 6) {
i <- i + 1
if (i == 3) {
next
}
print(i)
}
27
When the loop passes the value 3, it will skip it and continue to loop.
If the loop passes the values ranging from 1 to 5, it prints "No Yahtzee". Whenever it passes the
value 6, it prints "Yahtzee!".
R For Loop
For Loops
A for loop is used for iterating over a sequence:
Example
for (x in 1:10) {
print(x)
}
This is less like the for keyword in other programming languages, and works more like an
iterator method as found in other object-oriented programming languages.
With the for loop we can execute a set of statements, once for each item in a vector, array, list,
etc..
You will learn about lists and vectors, etc in a later chapter.
Example
Print every item in a list:
fruits <- list("apple", "banana", "cherry")
for (x in fruits) {
print(x)
}
Example
Print the number of dices:
28
dice <- c(1, 2, 3, 4, 5, 6)
for (x in dice) {
print(x)
}
The for loop does not require an indexing variable to set beforehand, like with while loops.
Break
With the break statement, we can stop the loop before it has looped through all the items:
Example
Stop the loop at "cherry":
fruits <- list("apple", "banana", "cherry")
for (x in fruits) {
if (x == "cherry") {
break
}
print(x)
}
The loop will stop at "cherry" because we have chosen to finish the loop by using
the break statement when x is equal to "cherry" (x == "cherry").
Next
With the next statement, we can skip an iteration without terminating the loop:
Example
Skip "banana":
fruits <- list("apple", "banana", "cherry")
for (x in fruits) {
if (x == "banana") {
next
}
print(x)
}
When the loop passes "banana", it will skip it and continue to loop.
Yahtzee!
If .. Else Combined with a For Loop
To demonstrate a practical example, let us say we play a game of Yahtzee!
Example
29
Print "Yahtzee!" If the dice number is 6:
dice <- 1:6
for(x in dice) {
if (x == 6) {
print(paste("The dice number is", x, "Yahtzee!"))
} else {
print(paste("The dice number is", x, "Not Yahtzee"))
}
}
If the loop reaches the values ranging from 1 to 5, it prints "No Yahtzee" and its number. When
it reaches the value 6, it prints "Yahtzee!" and its number.
R Nested Loops
Nested Loops
It is also possible to place a loop inside another loop. This is called a nested loop:
Example
Print the adjective of each fruit in a list:
adj <- list("red", "big", "tasty")
output:
[1] "red apple"
[1] "red banana"
[1] "red cherry"
[1] "big apple"
[1] "big banana"
[1] "big cherry"
[1] "tasty apple"
[1] "tasty banana"
[1] "tasty cherry"
R Functions
30
A function is a block of code which only runs when it is called.
You can pass data, known as parameters, into a function.
A function can return data as a result.
Creating a Function
To create a function, use the function() keyword:
Example
my_function <- function() { # create a function with the name my_function
print("Hello World!")
}
Call a Function
To call a function, use the function name followed by parenthesis, like my_function():
Example
my_function <- function() {
print("Hello World!")
}
Arguments
Information can be passed into functions as arguments.
Arguments are specified after the function name, inside the parentheses. You can add as many
arguments as you want, just separate them with a comma.
The following example has a function with one argument (fname). When the function is called,
we pass along a first name, which is used inside the function to print the full name:
Example
my_function <- function(fname) {
paste(fname, "Griffin")
}
my_function("Peter")
my_function("Lois")
my_function("Stewie")
Parameters or Arguments?
The terms "parameter" and "argument" can be used for the same thing: information that are
passed into a function.
From a function's perspective:
A parameter is the variable listed inside the parentheses in the function definition.
An argument is the value that is sent to the function when it is called.
31
Number of Arguments
By default, a function must be called with the correct number of arguments. Meaning that if
your function expects 2 arguments, you have to call the function with 2 arguments, not more,
and not less:
Example
This function expects 2 arguments, and gets 2 arguments:
my_function <- function(fname, lname) {
paste(fname, lname)
}
my_function("Peter", "Griffin")
If you try to call the function with 1 or 3 arguments, you will get an error:
Example
This function expects 2 arguments, and gets 1 argument:
my_function <- function(fname, lname) {
paste(fname, lname)
}
my_function("Peter")
my_function("Sweden")
my_function("India")
my_function() # will get the default value, which is Norway
my_function("USA")
Return Values
To let a function return a result, use the return() function:
Example
my_function <- function(x) {
return (5 * x)
}
print(my_function(3))
32
print(my_function(5))
print(my_function(9))
R Nested Functions
Nested Functions
There are two ways to create a nested function:
• Call a function within another function.
• Write a function within a function.
Example
Call a function within another function:
Nested_function <- function(x, y) {
a <- x + y
return(a)
}
Nested_function(Nested_function(2,2), Nested_function(3,3))
Example Explained
The function tells x to add y.
The first input Nested_function(2,2) is "x" of the main function.
The second input Nested_function(3,3) is "y" of the main function.
The output is therefore (2+2) + (3+3) = 10.
Example
Write a function within a function:
Outer_func <- function(x) {
Inner_func <- function(y) {
a <- x + y
return(a)
}
return (Inner_func)
}
output <- Outer_func(3) # To call the Outer_func
output(5)
Example Explained
33
You cannot directly call the function because the Inner_func has been defined (nested) inside
the Outer_func.
We need to call Outer_func first in order to call Inner_func as a second step.
We need to create a new variable called output and give it a value, which is 3 here.
We then print the output with the desired value of "y", which in this case is 5.
The output is therefore 8 (3 + 5).
More explanation
When a function with an argument is assigned to a variable in R programming, the variable
becomes a reference to that function, not the result of calling the function with a specific
argument.
Here's a breakdown of what happens:
1. The function object is stored: The function itself, including its definition and the
arguments it expects, is treated as an object in R. When you assign a function to a
variable, you are essentially storing this function object in that variable.
2. No execution occurs at assignment: The code within the function is not executed at the
moment of assignment. The argument you might be thinking of is part of the function's
definition, not something being passed to it during the assignment.
3. The variable is now a function: The variable you've assigned the function to can now be
used to call that function. You can then pass arguments to the variable (which is now
acting as the function) to execute the function's code.
Think of it like this:
Imagine you have a recipe for making a cake.
• The recipe itself is the function. It has steps (the code) and ingredients it needs (the
arguments).
• Assigning the recipe to a variable is like putting that recipe in a cookbook and labeling
it. You're not making the cake yet, you're just storing the instructions.
• Using the variable to call the function is like taking the recipe out of the cookbook and
following the steps, adding the ingredients you want. This is when the cake is actually
made.
Example:
Copy# Define a function that takes an argument and doubles it
my_function <- function(x) {
return(x * 2)
}
34
print(result)
In this example:
• my_function is the original function.
• my_variable <- my_function assigns the function object to my_variable. No calculation
happens here.
• my_variable(5) calls the function that my_variable refers to, passing 5 as the argument x.
This is when the multiplication actually occurs.
In summary, assigning a function with an argument to a variable in R makes the variable a
callable function that you can then use with specific arguments to get a result. It does not
execute the function with an argument at the time of assignment.
R Function Recursion
Recursion
R also accepts function recursion, which means a defined function can call itself.
Recursion is a common mathematical and programming concept. It means that a function calls
itself. This has the benefit of meaning that you can loop through data to reach a result.
The developer should be very careful with recursion as it can be quite easy to slip into writing a
function which never terminates, or one that uses excess amounts of memory or processor
power. However, when written correctly, recursion can be a very efficient and mathematically-
elegant approach to programming.
In this example, tri_recursion() is a function that we have defined to call itself ("recurse"). We
use the k variable as the data, which decrements (-1) every time we recurse. The recursion ends
when the condition is not greater than 0 (i.e. when it is 0).
To a new developer it can take some time to work out how exactly this works, best way to find
out is by testing and modifying it.
Example
tri_recursion <- function(k) {
if (k > 0) {
result <- k + tri_recursion(k - 1)
print(result)
} else {
result = 0
return(result)
}
}
tri_recursion(6)
35
2. The Statement:
• k + tri_recursion(k - 1): This part describes how the result of the current function call is
calculated. It's the sum of the current value of k and the result of the recursive call with
k - 1.
• result <- ...: This assigns the calculated value to a variable named result.
Putting it Together:
This statement implies that the function tri_recursion is designed to calculate something that is
the sum of the current value of k and the result of the same calculation for k-1.
Common Use Case: Summation
This pattern is very common for calculating the sum of numbers from 1 up to k. Let's look at an
example of what the tri_recursion function might look like:
36
So, tri_recursion(6) would return 21, which is the sum of 1, 2, 3, 4, 5 and 6.
Global Variables
Variables that are created outside of a function are known as global variables.
Global variables can be used by everyone, both inside of functions and outside.
Example
Create a variable outside of a function and use it inside the function:
my_function()
If you create a variable with the same name inside a function, this variable will be local, and can
only be used inside the function. The global variable with the same name will remain as it was,
global and with the original value.
Example
Create a variable inside of a function with the same name as the global variable:
If you try to print txt, it will return "global variable" because we are printing txt outside the
function.
37
my_function <- function() {
txt <<- "fantastic"
paste("R is", txt)
}
my_function()
print(txt)
output:
[1] "R is fantastic"
[1] "fantastic"
Also, use the global assignment operator if you want to change a global variable inside a
function:
Example
To change the value of a global variable inside a function, refer to the variable by using the
global assignment operator <<-:
output:
[1] "R is fantastic"
[1] "R is fantastic"
R Data Structures
Data Structures
Data structures are used to store and organize values.
R provides many built-in data structures. Each is used to handle data in different ways:
• Vectors
• Lists
• Matrices
• Arrays
• Data Frames
We will explore all of them in detail later, but for now, here's a quick introduction to each one.
38
Vectors
A vector is the most basic data structure in R. It contains a list of items of the same type.
Example
# Vector of strings
fruits <- c("banana", "apple", "orange")
# Print fruits
fruits
Lists
A list can hold different types of data in one structure. You can combine numbers, strings,
vectors, and even other lists.
Example
# List of strings
thislist <- list("apple", "banana", 50, 100)
Matrices
A matrix is a 2D data structure where all elements are of the same type. It is like a table with
rows and columns.
Example
# Create a matrix
thismatrix <- matrix(c(1,2,3,4,5,6), nrow = 3, ncol = 2)
Arrays
An array is like a matrix but can have more than two dimensions. It stores elements of the same
type in multiple dimensions.
Example
# An array with one dimension with values ranging from 1 to 24
thisarray <- c(1:24)
thisarray
39
Arrays are useful for working with 3D or higher-dimensional data.
Data Frames
A data frame is like a table in a spreadsheet. It can hold different types of data across multiple
columns.
Example
# Create a data frame
Data_Frame <- [Link] (
Training = c("Strength", "Stamina", "Other"),
Pulse = c(100, 150, 120),
Duration = c(60, 30, 45)
)
Summary
Data Contains Same Use Case
Structure Type?
Next, let's take a closer look at each data structure in more detail.
R Vectors
Vectors
A vector is simply a list of items that are of the same type.
To combine the list of items to a vector, use the c() function and separate the items by a comma.
In the example below, we create a vector variable called fruits, that combine strings:
Example
40
# Vector of strings
fruits <- c("banana", "apple", "orange")
# Print fruits
fruits
# Print numbers
numbers
You can also create numerical values with decimals in a sequence, but note that if the last
element does not belong to the sequence, it is not used:
Example
# Vector with numerical decimals in a sequence
numbers1 <- 1.5:6.5
numbers1
Result:
[1] 1.5 2.5 3.5 4.5 5.5 6.5
# Vector with numerical decimals in a sequence where the last element is not used
numbers2 <- 1.5:6.3
numbers2
Result:
[1] 1.5 2.5 3.5 4.5 5.5
Vector Length
To find out how many items a vector has, use the length() function:
41
Example
fruits <- c("banana", "apple", "orange")
length(fruits)
output: [1] 3
Sort a Vector
To sort items in a vector alphabetically or numerically, use the sort() function:
Example
fruits <- c("banana", "apple", "orange", "mango", "lemon")
numbers <- c(13, 3, 5, 7, 20, 2)
output:
[1] "apple" "banana" "lemon" "mango" "orange"
[1] 2 3 5 7 13 20
Access Vectors
You can access the vector items by referring to its index number inside brackets []. The first item
has index 1, the second item has index 2, and so on:
Example
fruits <- c("banana", "apple", "orange")
You can also access multiple elements by referring to different index positions with
the c() function:
Example
fruits <- c("banana", "apple", "orange", "mango", "lemon")
You can also use negative index numbers to access all items except the ones specified:
Example
fruits <- c("banana", "apple", "orange", "mango", "lemon")
42
Change an Item
To change the value of a specific item, refer to the index number:
Example
fruits <- c("banana", "apple", "orange", "mango", "lemon")
# Print fruits
fruits
output:
[1] "pear" "apple" "orange" "mango" "lemon"
Repeat Vectors
To repeat vectors, use the rep() function:
Example
Repeat each value:
repeat_each <- rep(c(1,2,3), each = 3)
repeat_each
output: [1] 1 1 1 2 2 2 3 3 3
Example
Repeat the sequence of the vector:
repeat_times <- rep(c(1,2,3), times = 3)
repeat_times
output: [1] 1 2 3 1 2 3 1 2 3
Example
Repeat each value independently:
repeat_indepent <- rep(c(1,2,3), times = c(5,2,1))
repeat_indepent
output: [1] 1 1 1 1 1 2 2 3
43
numbers <- 1:10
numbers
output: [1] 1 2 3 4 5 6 7 8 9 10
Note: The seq() function has three parameters: from is where the sequence starts, to is where
the sequence stops, and by is the interval of the sequence.
R Lists
Lists
A list in R can contain many different data types inside it. A list is a collection of data which is
ordered and changeable.
To create a list, use the list() function:
Example
# List of strings
thislist <- list("apple", "banana", "cherry")
Access Lists
You can access the list items by referring to its index number, inside brackets. The first item has
index 1, the second item has index 2, and so on:
Example
thislist <- list("apple", "banana", "cherry")
thislist[1]
44
# Print the updated list
thislist
List Length
To find out how many items a list has, use the length() function:
Example
thislist <- list("apple", "banana", "cherry")
length(thislist)
append(thislist, "orange")
45
thislist <- list("apple", "banana", "cherry")
Range of Indexes
You can specify a range of indexes by specifying where to start and where to end the range, by
using the : operator:
Example
Return the second, third, fourth and fifth item:
thislist <- list("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
(thislist)[2:5]
Note: The search will start at index 2 (included) and end at index 5 (included).
Remember that the first item has index 1.
for (x in thislist) {
print(x)
}
list3
output:
[[1]]
[1] "a"
46
[[2]]
[1] "b"
[[3]]
[1] "c"
[[4]]
[1] 1
[[5]]
[1] 2
[[6]]
[1] 3
R Matrices
Matrices
A matrix is a two dimensional data set with columns and rows.
A column is a vertical representation of data, while a row is a horizontal representation of data.
A matrix can be created with the matrix() function. Specify the nrow and ncol parameters to get
the amount of rows and columns:
Example
# Create a matrix
thismatrix <- matrix(c(1,2,3,4,5,6), nrow = 3, ncol = 2)
# Print the matrix
thismatrix
output:
[,1] [,2]
[1,] 1 4
[2,] 2 5
[3,] 3 6
47
output:
[,1] [,2]
[1,] "apple" "cherry"
[2,] "banana" "orange"
The whole row can be accessed if you specify a comma after the number in the bracket:
Example
thismatrix <- matrix(c("apple", "banana", "cherry", "orange"), nrow = 2, ncol = 2)
thismatrix[2,]
The whole column can be accessed if you specify a comma before the number in the bracket:
Example
thismatrix <- matrix(c("apple", "banana", "cherry", "orange"), nrow = 2, ncol = 2)
thismatrix[,2]
thismatrix[c(1,2),]
output:
[,1] [,2] [,3]
[1,] "apple" "orange" "pear"
[2,] "banana" "grape" "melon"
48
Access More Than One Column
More than one column can be accessed if you use the c() function:
Example
thismatrix <-
matrix(c("apple", "banana", "cherry", "orange","grape", "pineapple", "pear", "melon", "fig"),
nrow = 3, ncol = 3)
thismatrix[, c(1,2)]
output:
[,1] [,2]
[1,] "apple" "orange"
[2,] "banana" "grape"
[3,] "cherry" "pineapple"
output:
[,1] [,2] [,3] [,4]
[1,] "apple" "orange" "pear" "strawberry"
[2,] "banana" "grape" "melon" "blueberry"
[3,] "cherry" "pineapple" "fig" "raspberry"
Note: The cells in the new column must be of the same length as the existing matrix.
Use the rbind() function to add additional rows in a Matrix:
Example
thismatrix <-
matrix(c("apple", "banana", "cherry", "orange","grape", "pineapple", "pear", "melon", "fig"),
nrow = 3, ncol = 3)
49
# Print the new matrix
newmatrix
output:
[,1] [,2] [,3]
[1,] "apple" "orange" "pear"
[2,] "banana" "grape" "melon"
[3,] "cherry" "pineapple" "fig"
[4,] "strawberry" "blueberry" "raspberry"
Note: The cells in the new row must be of the same length as the existing matrix.
thismatrix
output:
[1] "mango" "pineapple"
50
thismatrix <- matrix(c("apple", "banana", "cherry", "orange"), nrow = 2, ncol = 2)
dim(thismatrix)
output:
[1] 2 2
Matrix Length
Use the length() function to find the dimension of a Matrix:
Example
thismatrix <- matrix(c("apple", "banana", "cherry", "orange"), nrow = 2, ncol = 2)
length(thismatrix)
output:
[1] 4
Total cells in the matrix is the number of rows multiplied by number of columns.
In the example above: Dimension = 2*2 = 4.
output:
[1] "apple"
[1] "cherry"
[1] "banana"
[1] "orange"
51
# Adding it as a rows
Matrix_Combined <- rbind(Matrix1, Matrix2)
Matrix_Combined
Output:
[,1] [,2]
[1,] "apple" "cherry"
[2,] "banana" "grape"
[3,] "orange" "pineapple"
[4,] "mango" "watermelon"
# Adding it as a columns
Matrix_Combined <- cbind(Matrix1, Matrix2)
Matrix_Combined
Output:
[,1] [,2] [,3] [,4]
[1,] "apple" "cherry" "orange" "pineapple"
[2,] "banana" "grape" "mango" "watermelon"
Exercise
Can you determine what this program do?
xr_means[1] = mean(x[1,])
xr_means[2] = mean(x[2,])
xr_means[3] = mean(x[3,])
xr_means[4] = mean(x[4,])
xr_means[5] = mean(x[5,])
52
"This is the Row-wise average of the matrix"
xr_means
R Arrays
Arrays
Compared to matrices, arrays can have more than two dimensions.
We can use the array() function to create an array, and the dim parameter to specify the
dimensions:
Example
# An array with one dimension with values ranging from 1 to 24
thisarray <- c(1:24)
thisarray
[1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
,,1
,,2
Example Explained
In the example above we create an array with the values 1 to 24.
How does dim=c(4,3,2) work?
The first and second number in the bracket specifies the amount of rows and columns.
The last number in the bracket specifies how many dimensions we want.
Note: Arrays can only have one data type.
53
Access Array Items
You can access the array elements by referring to the index position. You can use the [] brackets
to access the desired elements from an array:
Example
thisarray <- c(1:24)
multiarray <- array(thisarray, dim = c(4, 3, 2))
multiarray[2, 3, 2]
output: [1] 22
# Access all the items from the first row from matrix one
multiarray <- array(thisarray, dim = c(4, 3, 2))
multiarray[c(1),,1]
output: [1] 1 5 9
# Access all the items from the first column from matrix one
multiarray <- array(thisarray, dim = c(4, 3, 2))
multiarray[,c(1),1]
output: [1] 1 2 3 4
A comma (,) before c() means that we want to access the column.
A comma (,) after c() means that we want to access the row.
2 %in% multiarray
54
Example
thisarray <- c(1:24)
multiarray <- array(thisarray, dim = c(4, 3, 2))
dim(multiarray)
output: [1] 4 3 2
Array Length
Use the length() function to find the dimension of an array:
Example
thisarray <- c(1:24)
multiarray <- array(thisarray, dim = c(4, 3, 2))
length(multiarray)
output: [1] 24
for(x in multiarray){
print(x)
}
R Data Frames
Data Frames
Data Frames are data displayed in a format as a table.
Data Frames can have different types of data inside it. While the first column can be character,
the second and third can be numeric or logical. However, each column should have the same
type of data.
Use the [Link]() function to create a data frame:
Example
# Create a data frame
Data_Frame <- [Link] (
Training = c("Strength", "Stamina", "Other"),
Pulse = c(100, 150, 120),
Duration = c(60, 30, 45)
)
55
# Print the data frame
Data_Frame
Output:
Training Pulse Duration
1 Strength 100 60
2 Stamina 150 30
3 Other 120 45
Data_Frame
summary(Data_Frame)
Output:
Training Pulse Duration
1 Strength 100 60
2 Stamina 150 30
3 Other 120 45
Access Items
We can use single brackets [ ], double brackets [[ ]] or $ to access columns from a data frame:
Example
Data_Frame <- [Link] (
Training = c("Strength", "Stamina", "Other"),
Pulse = c(100, 150, 120),
Duration = c(60, 30, 45)
56
)
Data_Frame[1]
Data_Frame[["Training"]]
Data_Frame$Training
Output:
Training
1 Strength
2 Stamina
3 Other
[1] Strength Stamina Other
Levels: Other Stamina Strength
[1] Strength Stamina Other
Levels: Other Stamina Strength
Add Rows
Use the rbind() function to add new rows in a Data Frame:
Example
Data_Frame <- [Link] (
Training = c("Strength", "Stamina", "Other"),
Pulse = c(100, 150, 120),
Duration = c(60, 30, 45)
)
Output:
Training Pulse Duration
1 Strength 100 60
2 Stamina 150 30
3 Other 120 45
4 Speed 110 110
Add Columns
Use the cbind() function to add new columns in a Data Frame:
Example
57
Data_Frame <- [Link] (
Training = c("Strength", "Stamina", "Other"),
Pulse = c(100, 150, 120),
Duration = c(60, 30, 45)
)
Output:
Training Pulse Duration Steps
1 Strength 100 60 1000
2 Stamina 150 30 6000
3 Other 120 45 2000
Output:
Pulse Duration
2 150 30
3 120 45
58
Duration = c(60, 30, 45)
)
dim(Data_Frame)
You can also use the ncol() function to find the number of columns and nrow() to find the
number of rows:
Example
Data_Frame <- [Link] (
Training = c("Strength", "Stamina", "Other"),
Pulse = c(100, 150, 120),
Duration = c(60, 30, 45)
)
ncol(Data_Frame)
nrow(Data_Frame)
length(Data_Frame)
59
New_Data_Frame <- rbind(Data_Frame1, Data_Frame2)
New_Data_Frame
Output:
Training Pulse Duration
1 Strength 100 60
2 Stamina 150 30
3 Other 120 45
4 Stamina 140 30
5 Stamina 150 30
6 Strength 160 20
And use the cbind() function to combine two or more data frames in R horizontally:
Example
Data_Frame3 <- [Link] (
Training = c("Strength", "Stamina", "Other"),
Pulse = c(100, 150, 120),
Duration = c(60, 30, 45)
)
Output:
Training Pulse Duration Steps Calories
1 Strength 100 60 3000 300
2 Stamina 150 30 6000 400
3 Other 120 45 2000 300
R Plotting
Plot
The plot() function is used to draw points (markers) in a diagram.
The function takes parameters for specifying points in the diagram.
Parameter 1 specifies points on the x-axis.
Parameter 2 specifies points on the y-axis.
At its simplest, you can use the plot() function to plot two numbers against each other:
60
Example
Draw one point in the diagram, at position (1) and position (3):
plot(1, 3)
Result:
61
Multiple Points
You can plot as many points as you like, just make sure you have the same number of points in
both axis:
Example
plot(c(1, 2, 3, 4, 5), c(3, 7, 8, 9, 12))
Result:
For better organization, when you have many values, it is better to use variables:
Example
x <- c(1, 2, 3, 4, 5)
y <- c(3, 7, 8, 9, 12)
plot(x, y)
Result:
62
Sequences of Points
If you want to draw dots in a sequence, on both the x-axis and the y-axis, use the : operator:
Example
plot(1:10)
Result:
Draw a Line
The plot() function also takes a type parameter with the value l to draw a line to connect all the
points in the diagram:
Example
plot(1:10, type="l")
Result:
63
Plot Labels
The plot() function also accept other parameters, such as main, xlab and ylab if you want to
customize the graph with a main title and different labels for the x and y-axis:
Example
plot(1:10, main="My Graph", xlab="The x-axis", ylab="The y axis")
Result:
Graph Appearance
There are many other parameters you can use to change the appearance of the points.
Colors
Use col="color" to add a color to the points:
Example
plot(1:10, col="red")
Result:
64
Size
Use cex=number to change the size of the points (1 is default, while 0.5 means 50% smaller,
and 2 means 100% larger):
Example
plot(1:10, cex=2)
Result:
Point Shape
Use pch with a value from 0 to 25 to change the point shape format:
Example
plot(1:10, pch=25, cex=2)
Result:
The values of the pch parameter ranges from 0 to 25, which means that we can choose up to 26
different types of point shapes:
65
R Line
Line Graphs
A line graph has a line that connects all the points in a diagram.
To create a line, use the plot() function and add the type parameter with a value of "l":
Example
plot(1:10, type="l")
Result:
Line Color
The line color is black by default. To change the color, use the col parameter:
Example
66
plot(1:10, type="l", col="blue")
Result:
Line Width
To change the width of the line, use the lwd parameter (1 is default, while 0.5 means 50%
smaller, and 2 means 100% larger):
Example
plot(1:10, type="l", lwd=2)
Result:
67
Line Styles
The line is solid by default. Use the lty parameter with a value from 0 to 6 to specify the line
format.
For example, lty=3 will display a dotted line instead of a solid line:
Example
plot(1:10, type="l", lwd=5, lty=3)
Result:
68
Available parameter values for lty:
• 0 removes the line
• 1 displays a solid line
• 2 displays a dashed line
• 3 displays a dotted line
• 4 displays a "dot dashed" line
• 5 displays a "long dashed" line
• 6 displays a "two dashed" line
Multiple Lines
To display more than one line in a graph, use the plot() function together with
the lines() function:
Example
line1 <- c(1,2,3,4,5,10)
line2 <- c(2,5,7,8,9,10)
R Scatter Plot
Scatter Plots
You learned from the Plot section that the plot() function is used to plot numbers against each
other.
69
A "scatter plot" is a type of plot used to display the relationship between two numerical
variables, and plots one dot for each observation.
It needs two vectors of same length, one for the x-axis (horizontal) and one for the y-axis
(vertical):
Example
x <- c(5,7,8,7,2,2,9,4,11,12,9,6)
y <- c(99,86,87,88,111,103,87,94,78,77,85,86)
plot(x, y)
Result:
The observation in the example above should show the result of 12 cars passing by.
That might not be clear for someone who sees the graph for the first time, so let's add a header
and different labels to describe the scatter plot better:
Example
x <- c(5,7,8,7,2,2,9,4,11,12,9,6)
y <- c(99,86,87,88,111,103,87,94,78,77,85,86)
70
To recap, the observation in the example above is the result of 12 cars passing by.
The x-axis shows how old the car is.
The y-axis shows the speed of the car when it passes.
Are there any relationships between the observations?
It seems that the newer the car, the faster it drives, but that could be a coincidence, after all we
only registered 12 cars.
Compare Plots
In the example above, there seems to be a relationship between the car speed and age, but
what if we plot the observations from another day as well? Will the scatter plot tell us
something else?
To compare the plot with another plot, use the points() function:
Example
Draw two plots on the same figure:
# day one, the age and speed of 12 cars:
x1 <- c(5,7,8,7,2,2,9,4,11,12,9,6)
y1 <- c(99,86,87,88,111,103,87,94,78,77,85,86)
71
plot(x1, y1, main="Observation of Cars", xlab="Car age", ylab="Car speed", col="red", cex=2)
points(x2, y2, col="blue", cex=2)
Result:
Note: To be able to see the difference of the comparison, you must assign different colors to the
plots (by using the col parameter). Red represents the values of day 1, while blue represents day
2. Note that we have also added the cex parameter to increase the size of the dots.
Conclusion of observation: By comparing the two plots, I think it is safe to say that they both
gives us the same conclusion: the newer the car, the faster it drives.
R Pie Charts
Pie Charts
A pie chart is a circular graphical view of data.
Use the pie() function to draw pie charts:
Example
# Create a vector of pies
x <- c(10,20,30,40)
72
Example Explained
As you can see the pie chart draws one pie for each value in the vector (in this case 10, 20, 30,
40).
By default, the plotting of the first pie starts from the x-axis and move counterclockwise.
Note: The size of each pie is determined by comparing the value with all the other values, by
using this formula:
The value divided by the sum of all values: x/sum(x)
Start Angle
You can change the start angle of the pie chart with the [Link] parameter.
The value of [Link] is defined with angle in degrees, where default angle is 0.
Example
Start the first pie at 90 degrees:
# Create a vector of pies
x <- c(10,20,30,40)
# Display the pie chart and start the first pie at 90 degrees
pie(x, [Link] = 90)
Result:
Colors
You can add a color to each pie with the col parameter:
Example
# Create a vector of colors
colors <- c("blue", "yellow", "green", "black")
74
Legend
To add a list of explanation for each pie, use the legend() function:
Example
# Create a vector of labels
mylabel <- c("Apples", "Bananas", "Cherries", "Dates")
75
The legend can be positioned as either:
bottomright, bottom, bottomleft, left, topleft, top, topright, right, center
R Bar Charts
Bar Charts
A bar chart uses rectangular bars to visualize data. Bar charts can be displayed horizontally or
vertically. The height or length of the bars are proportional to the values they represent.
Use the barplot() function to draw a vertical bar chart:
Example
# x-axis values
x <- c("A", "B", "C", "D")
# y-axis values
y <- c(2, 4, 6, 8)
barplot(y, [Link] = x)
Result:
76
Example Explained
• The x variable represents values in the x-axis (A,B,C,D)
• The y variable represents values in the y-axis (2,4,6,8)
• Then we use the barplot() function to create a bar chart of the values
• [Link] defines the names of each observation in the x-axis
Bar Color
Use the col parameter to change the color of the bars:
Example
x <- c("A", "B", "C", "D")
y <- c(2, 4, 6, 8)
77
Density / Bar Texture
To change the bar texture, use the density parameter:
Example
x <- c("A", "B", "C", "D")
y <- c(2, 4, 6, 8)
Bar Width
Use the width parameter to change the width of the bars:
Example
x <- c("A", "B", "C", "D")
y <- c(2, 4, 6, 8)
78
Horizontal Bars
If you want the bars to be displayed horizontally instead of vertically, use horiz=TRUE:
Example
x <- c("A", "B", "C", "D")
y <- c(2, 4, 6, 8)
79