0% found this document useful (0 votes)
11 views39 pages

Cours R

The document is a comprehensive guide to R programming, covering installation, workspace overview, and fundamental concepts such as objects, vectors, and functions. It includes exercises and quizzes to reinforce learning and provides insights into using RStudio as an Integrated Development Environment (IDE). The module aims to equip participants with the necessary skills for effective data analysis and visualization using R.

Uploaded by

swilim2002
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views39 pages

Cours R

The document is a comprehensive guide to R programming, covering installation, workspace overview, and fundamental concepts such as objects, vectors, and functions. It includes exercises and quizzes to reinforce learning and provides insights into using RStudio as an Integrated Development Environment (IDE). The module aims to equip participants with the necessary skills for effective data analysis and visualization using R.

Uploaded by

swilim2002
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

R Programming

Dr. BOUATELLI Mohamed & Dr. AZZAZ Rachid


2024-02 2024-04
Programming
R-2024
Table of contents

Objectives 4
I - Chapter 1: Introduction to the R Language 5
1. Getting started with R software ................................................................................5
2. Overview of the workspace: commands and packages in R ...................................7
3. Integrated Development Environment (IDE)............................................................8
4. Exploring the R-Studio IDE ......................................................................................10
II - Chapter 2 - Objects, Vectors, and Functions 12
1. The R code................................................................................................................12
1.1. R command .....................................................................................................................................12
1.2. comments in R.................................................................................................................................12
1.3. Objects .............................................................................................................................................12
1.4. Mathematical and comparaison opertators ..................................................................................13
1.5. some notions ...................................................................................................................................13
1.6. data types in R programming .........................................................................................................14
1.7. Vectors .............................................................................................................................................15
1.8. Lists ..................................................................................................................................................20

2. Functions in R ..........................................................................................................20
2.1. Type of Functions in R .....................................................................................................................20
2.2. help on R for Built-in Functions ......................................................................................................21
2.3. a user-defined function...................................................................................................................21

III - Exercice series 22


1. Quiz: N°(1) ................................................................................................................22
2. Quiz: N°(2) ................................................................................................................22
3. Quiz: N°(3) ................................................................................................................22
4. Quiz: N°(4) ................................................................................................................22
5. Quiz: N°(5) ................................................................................................................23
6. Quiz: N°(6) ................................................................................................................23
7. Quiz: N°(7) ................................................................................................................23
8. Quiz: N°(8) ................................................................................................................23
IV - Chapter 3- Mastering R Studio: Options, Importing, Exporting, and Packages 24
1. Data Import and Export Management in R .............................................................24
V - Chapter 4: Data Frames (data.frame) 28
1. Creating a data.frame..............................................................................................28

2
Table of contents

2. Summarize the Data ................................................................................................29


3. Access Items.............................................................................................................30
4. Add Rows..................................................................................................................30
5. Add Columns ............................................................................................................31
6. Remove Rows and Columns ....................................................................................32
7. Access an element ...................................................................................................32
8. Transform variables.................................................................................................33
9. Cross-tabulation ......................................................................................................33
Exercise solutions 35
Bibliography 38

3
Objectives

R is both statistical software and a programming language used for manipulating data, creating
visualizations, and conducting statistical analyses on that data. For several years, R has established itself
as the reference for data analysis and graph production in a wide range of industries. The goal of this
module is to explore the R software step by step, enabling participants to acquire the knowledge and
skills needed to work effectively in this environment.

4
Chapter 1: Introduction to the R
Language I

1. Getting started with R software

Definition

R is a versatile and open-source programming language and software environment designed


for statistical computing and data analysis. It provides a user-friendly interface (with IDEs) for
manipulating data, creating visualizations, and performing statistical analyses, making it an
essential tool for researchers, analysts, and professionals working with data.

Downloading and Installing R


Windows and OS X users can download R from CRAN, while Linux and Unix users can install R packages
using their package management tool.

Operating System Steps to Install R

1. Visit the CRAN website (cran.r-project.org)


2. Click on : Download R for Windows
Windows
3. Choose base and download the installer
4. Run the installer and follow on-screen prompts

1. Visit the CRAN website (cran.r-project.org)


2. Click on "Download R for (Mac) OS X"
Mac OS
3. Choose the latest version and download the pkg file
4. Run the pkg file and follow the installation prompts

1. Use the package manager for your distribution


2. For Debian/Ubuntu: sudo apt-get install r-base
Linux
3. For Fedora: sudo dnf install R
4. For openSUSE: sudo zypper install R

Example on Windows :

The CRAN homepage

5
Chapter 1: Introduction to the R Language

Download options

Download the R setup for Windows OS

CRAN mirror
A CRAN mirror is a global server hosting a copy of the Comprehensive R Archive Network (CRAN),
enabling users to download R software, packages, and resources. Choosing a closer CRAN mirror
enhances download speed during R installation or updates.

R Mirrors

Selecting a Mirror

6
Chapter 1: Introduction to the R Language

Starting R
Starting on Windows : When you start R, it opens a new window. The window includes a text pane,
called the R Console, where you enter R expressions

The R base interface

When R starts, what is the working directory?


The R working directory is the folder where R searches for and saves files. It has a default location when
you start a session.

Fucntion Meaning Example

check the
getwd() current working
directory in R

set working
setwd()
directory

2. Overview of the workspace: commands and packages in R


Entering Commands
You just simply enter expressions at the command prompt. R will evaluate them and print (display) the
result. You can use command-line editing to facilitate typing.
To get started, just treat R like a big calculator: enter an expression, and R will evaluate the expression
and print the result

7
Chapter 1: Introduction to the R Language

Example of a simple expression


R will prompt you for input until you type a complete expression. The expression max(1,3,5) is a
complete expression, so R stops reading input and evaluates what it’s got:

In contrast, “max(1,3,” is an incomplete expression, so R prompts you for more input. The prompt
changes from greater-than (>) to plus (+), letting you know that R expects more:

3. Integrated Development Environment (IDE)


An Integrated Development Environment (IDE) is a software package that provides tools for developing
and testing software. It automates developer tasks, reduces manual effort, and combines all tools in a
common framework 11 p.381 p.38. IDEs typically include features such as code editors, compilers,
debuggers, and other tools to make the process of writing, testing, and debugging code more efficient
22 p.38.

RStudio IDE
RStudio is an Integrated Development Environment (IDE) designed for the R programming language. It
offers a user-friendly interface with features such as a script (code) editor, console, data viewer, and
integrated tools for R package management, plotting, and project organization. RStudio is widely used
for R programming and data analysis tasks.

8
Chapter 1: Introduction to the R Language

Graphic 1 The R-Studio Interface

Download and install RStudio


Go to the RStudio download page: https://posit.co/download/rstudio-desktop/
Choose the appropriate version of RStudio for your operating system (Windows, macOS, or Linux)
Double-click the downloaded installer (.exe) file and Follow the on-screen instructions

Graphic 2 Downloading R-Studio

Graphic 3 detailed installation steps

9
Chapter 1: Introduction to the R Language

Graphic 3 detailed installation steps

4. Exploring the R-Studio IDE


R-Script
An R script is a file containing a series of R programming language commands and expressions. It is a
text file with the extension ".R" that typically contains a sequence of R code written to perform specific
tasks or analyses. R scripts are used to automate tasks, reproduce analyses, and organize code for
better maintainability.

Graphic 4
Key characteristics of R scripts include:
Plain Text Format: R scripts are plain text files, often created using a text editor or an Integrated
Development Environment (IDE) like RStudio. This makes them human-readable and easy to
share.
Code Sequences: R scripts consist of a sequence of R commands, statements, and expressions.
These can include data manipulations, statistical analyses, plotting, and more.
Reproducibility: One of the main advantages of using R scripts is the ability to achieve
reproducibility. By saving your R code in a script, others (or your future self) can rerun the script
to reproduce the same results.
Documentation: R scripts can include comments (lines preceded by the # symbol) to provide
explanations and documentation for the code. This helps make the code more understandable
for others and for future reference.
Functions and Control Structures: R scripts can define functions and use control structures
(e.g., loops and conditional statements) to create more complex and organized code.
Example :
1 x <- 10 # creates a numeric object 'x' with the value 10
2 vector <- c(1, 2, 3) # creates a numeric vector 'vector'

Run the Script:


To run a line of a script, put the cursor in the line you want to run and:
Click on the "Run" button in the toolbar, or
Use the keyboard shortcut Ctrl + Enter (Windows/Linux)
To run the entire script, select the entire you want to run by the the cursor or by using (Ctrl+A) and:
Click on the "Run" button in the toolbar, or
Use the keyboard shortcut Ctrl + Enter (Windows/Linux)

10
Chapter 1: Introduction to the R Language

Graphic 5 Run a script

The console
the console serves as an interactive interface for executing R commands and receiving immediate
feedback. Here are some key aspects of the console in RStudio:
Immediate Output: When you enter a command in the console and press Enter, R immediately
processes the command and displays the output or result right below the command
History:The console keeps a history of previously executed commands.
Variable Inspection : After executing commands that create variables or objects, the console displays
information about these objects, such as their values, types, and dimensions.
Error Messages and Warnings : If there are errors or warnings in your code, the console will display
relevant messages, helping you identify and address issues in your R script.
Interactive Help :You can access interactive help by typing ? followed by the function or topic you
want help with. The console will display relevant help documentation.

11
Chapter 2 - Objects, Vectors, and
Functions II

1. The R code
1.1. R command
A command refers to a line of code or a statement that instructs the R interpreter to perform a specific
action or computation. R commands can be simple, like assigning a value to a variable, or they can be
more complex, involving functions, data manipulation, statistical analysis, and more.
Example : (Variable Assignment)
1 x <- 10

Example : (Print Statement)


1 print("Hello, R!")

Example : ( Function Call)


1 mean_value <- mean(c(2, 4, 6, 8, 10))

1.2. comments in R
In R programming, comments are annotations within the code that are not executed as part of the
program. They are used to provide explanations, clarify code, or add notes for the programmer.
Comments in R are preceded by the hash symbol (#). Anything following the # on a line is treated as a
comment and is ignored by the R interpreter.
1 print("Hello, R!") # Displays the text "Hello, R!" in the console

1.3. Objects
In R programming, an object is often used interchangeably with the term "variable." In R, variables are
used to store and manipulate data. When you create a variable and assign a value to it, you are
essentially creating an object.

ls() - List Objects


The ls() function is used to list the names of objects (variables, functions, etc.) currently present in
the R workspace or a specified environment

rm() - Remove Objects: Definition

The rm() function is used to remove (delete) one or more objects from the R workspace. It helps in
freeing up memory by removing unnecessary objects.
Example:
1 rm(my_variable) # Remove the object 'my_variable' from the workspace

To remove multiple objects, you can provide a list of object names:


1 rm(obj1, obj2, obj3) # Remove multiple objects

12
Chapter 2 - Objects, Vectors, and Functions

To remove all objects in the workspace, you can use rm(list = ls()):
1 rm(list = ls()) # Remove all objects in the workspace

1.4. Mathematical and comparaison opertators

R’s mathematical operators and functions

Comparison operators in R

1.5. some notions


The zero before the decimal point in R
In R programming, if you have a numeric value less than 1 but greater than or equal to 0, you may write
it with a zero before the decimal point
1 x<-.5
2 print(x)
3 [1] 0.5 #result

13
Chapter 2 - Objects, Vectors, and Functions

Conventions for object names


In R programming, the following are not allowed when writing names for objects:
1. Starting with a number or (.number)
1 5x<-20 #starting with a mumber
2 Error: unexpected symbol in "5x"
3
4 .5x<-20 #starting with a mumber
5 Error: unexpected symbol in ".5x"

2. Using reserved words or system names such as break, else, for, function, if, in, next, repeat, return,
while, TRUE, FALSE, Inf, NA, NaN, NULL, NA_integer_, NA_real_, NA_complex_, NA_character_, ..., ..1,
..2, etc.
1 if<-10
2 Error: unexpected assignment in "if<-"

Using special characters other than period "." and underscore "_".
1 *x<-20
2 Error: unexpected '*' in "*"

The variables T and F default to the values TRUE and FALSE, respectively, but can be reassigned
1> T
2 [1] TRUE
3> F
4 [1] FALSE

reassigning :
> T<-10
>T
[1] 10
> F<-20
>F
[1] 20

1.6. data types in R programming


data types in R programming
Data Type Description Example

Numeric Real numbers with decimal points 3.14, -123.45

Integer Whole numbers without decimal points 42, -100

"hello", 'R
Character Textual data enclosed in quotes
programming'

Logical Binary data with TRUE or FALSE values TRUE, FALSE

Complex Numbers with real and imaginary parts 3 + 4i, -2.5 - 1.8i

Raw Raw binary data 0x3F, 0b11001010

"High", "Medium",
Factor Categorical data with fixed levels
"Low"

"2024-02-12",
Date & Time Dates, times, or date-time objects
"09:30:00"

14
Chapter 2 - Objects, Vectors, and Functions

In R, you can use the following functions to determine the type of an object:
typeof(): This function returns the type of an object as a string
Example :
1 > x<-10.2
2 > z<-TRUE
3 > typeof(x)
4 [1] "double"
5 > typeof(z)
6 [1] "logical"

1.7. Vectors
a) Vectors Creation and related functions and operations
Using the c() function:
You can create a vector by combining elements using the c() function.
Example :
1 > v <- c(1, 2, 3, 4, 5)
2 > print(v)
3 [1] 1 2 3 4 5

Using the rep() function:


You can create a vector by repeating elements using the rep() function.
Example:
1 > v <- rep(0, times = 5);print(v)
2 [1] 0 0 0 0 0
3 > v2<-rep(1,5);print(v2)
4 [1] 1 1 1 1 1

Using the seq() function:


You can create a sequence of numbers using the seq() function.
Example:
1 > v<-seq(from = 1, to = 10, by =2)
2 > print(v)
3 [1] 1 3 5 7 9

we can use the previous code like that


1 > v<-seq(1,10, by =2)
2 > print(v)
3 [1] 1 3 5 7 9

Using the colon operator:


You can create a sequence of consecutive numbers using the colon operator :.
Example:
1 > v <- 1:5
2> v
3 [1] 1 2 3 4 5

15
Chapter 2 - Objects, Vectors, and Functions

Using the c() function with concatenation:


You can create a vector by concatenating other vectors or elements using the c() function.
1 > vector1 <- c(1, 2, 3)
2 > vector2 <- c(4, 5, 6)
3 > vector3 <- c(vector1, vector2)
4 > print(vector3)
5 [1] 1 2 3 4 5 6

the functions str()


the function str() stands for "structure" and is used to display the internal structure of R objects.
When applied to an R object, such as a vector, matrix, data frame, or list, the str() function provides
detailed information about the object's type, size, and content.
Example:
1 > vector1 <- c(1, 2, 3)
2 > str(vector1)
3 num [1:3] 1 2 3

The length() function


The length() function is used to determine the number of elements in an object, such as a vector,
list, matrix, or array. It returns an integer value representing the size or length of the object along its
first dimension.
1 > v <- c(1, 2, 3, 4, 5)
2 > length(v)
3 [1] 5

label-value vector
To add labels from one vector and values from another vector in R, you can use the names() function
to assign labels to the elements of the first vector
1 l <- c("A", "B", "C") # Vector of labels
2 v <- c(10, 20, 30) # Vector of values
3
4 # Assign labels to the elements of the values vector
5 names(v) <- l
6v

you can add direcltly label when defining the vectos as follow :
1 v <- c(A=10, b=20, c=30) # Vector of labels and values
2v

Mathematical operations on vectors


Mathematical operations on vectors involve performing arithmetic operations (such as addition,
subtraction, multiplication, and division) on corresponding elements of two or more vectors.
1 v1 <- c(1, 2, 3)
2 v2 <- c(4,5,6)
3 v3<-v1+v2 #addition
4 v3

Vector indexing
The indexing in a vector is done using square brackets [ ]. One can extract an element from a vector by
its position or by its label, if it exists (in which case this approach is much safer).
Example (position index):
1 v <- c(A=10, b=20, c=30) # Vector of labels and values
2 v[1] #extract the value at position 1

16
Chapter 2 - Objects, Vectors, and Functions

Example (label index):


1 v <- c(A=10, b=20, c=30) # Vector of labels and values
2 v["A"] #extract the value at position 1
3
4A
5 10

You can extract a part or subset from a vector by specifying the start and end indexes within square
brackets.
Example :
1 v <- c(A=10, b=20, c=30) # Vector of labels and values
2 x<-v[1:2] #extract the part from index 01 to 2
3 print(x)
4
5A b
6 10 20

The numbers within brackets at the beginning of each line.


The numbers within brackets at the beginning of each line represent the index or position of each
element in the printed output.
Example :
1 > z<-c(1:30)
2> z
3 [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
4 [23] 23 24 25 26 27 28 29 30

The types of vectors in R


The types of vectors in R include:
1 # Numeric Vector (contains decimal numbers)
2 numeric_vector <- c(1.5, 2.3, 4.7)
3 print(numeric_vector) # Output: [1] 1.5 2.3 4.7
4
5 # Integer Vector (contains whole numbers)
6 integer_vector <- c(1L, 2L, 3L)
7 print(integer_vector) # Output: [1] 1 2 3
8
9 # Character Vector (contains text strings)
10 character_vector <- c("apple", "orange")
11 print(character_vector) # Output: [1] "apple" "orange"
12
13 # Logical Vector (contains boolean values)
14 logical_vector <- c(TRUE, FALSE, TRUE)
15 print(logical_vector) # Output: [1] TRUE FALSE TRUE
16
17 # Complex Vector (contains complex numbers)
18 complex_vector <- c(1+2i, 3-4i, 5+6i)
19 print(complex_vector) # Output: [1] 1+2i 3-4i 5+6i
20
21 # Raw Vector (contains raw bytes of data)
22 raw_vector <- as.raw(c(0x01, 0x02, 0x03))
23 print(raw_vector) # Output: [1] 01 02 03
24

Automatic conversions of vectors


vector must always consist of elements of the same type. But what happens if we still try to create a
vector with different types? Well, R will simply change the type of certain elements so that ultimately all
elements share the same type! This is called type conversion.

17
Chapter 2 - Objects, Vectors, and Functions

Example:
1 mon_vecteur = c(3.14, "A")
2 print(mon_vecteur)
3
4 [1] "3.14" "A"

example 02
1 x<-3.14
2 y<-"A"
3 mon_vecteur = c(x,y)
4 print(mon_vecteur)
5 [1] "3.14" "A"
6
7 typeof(x)
8 [1] "double"
9 typeof(y)
10 [1] "character"
11
12 typeof(mon_vecteur[1])
13 [1] "character"
14 typeof(mon_vecteur[2])
15 [1] "character"

as we can see R perform Automatic conversions.


The golden rule: the most important type prevails over the others.
The main rule used to convert the elements is rather simple: all elements are converted to the highest-
ranked type present in the vector, with types ranked in this order:
character > complex > double > integer > logical.

Functions of the form as.*()


There are functions, of the form as.*(), to perform explicit conversions.
here a list:
1 as.character() #converts an object to a character data type.
2 as.numeric() #converts an object to a numeric (floating-point) data type.
3 as.integer() #converts an object to an integer data type.
4 as.logical() #converts an object to a logical (Boolean) data type.
5 as.complex() #converts an object to a complex data type.

Example: (from numeric to character)


1 > x<-as.character(c(0, 1, 2, 3, 4))
2> x
3 [1] "0" "1" "2" "3" "4"

Example: (from character to numeric)


1 x <- as.numeric(c("0", "1", "2", "3", "4")) # character vector
2 typeof(x) # Check the data type of the vector x
3 [1] "double"
4
5 z <- as.integer(x) # Convert the vector x to integer type
6 print(z)
7 [1] 0 1 2 3 4
8
9 typeof(z) # Check the data type of the vector z
10 [1] "integer"

18
Chapter 2 - Objects, Vectors, and Functions

Functions of the form is.*()


The is.*() functions are used to check whether an object belongs to a specific data type. These
functions return a logical value (TRUE or FALSE) indicating whether the object is of the specified type
Example :
1 v <- c(1, 2, 3, 4, 5)
2 z <- is.numeric(v) # Check if the vector contains numeric values
3 print(z)

Replace, modify, or delete elements of a vector.


1 my_vector <- c(10, 20, 30, 40, 50) # Create a vector
2
3 # Replace an element
4 my_vector[3] <- 35 # Replace the third element (30) with 35
5 print(my_vector)
6 [1] 10 20 35 40 50
7
8 # Modify an element
9 my_vector[2] <- my_vector[2] * 2 # Double the value of the second element (20)
10 print(my_vector)
11 [1] 10 40 35 40 50
12
13 # Delete an element
14 my_vector <- my_vector[-4] # Delete the fourth element (40)
15 print(my_vector)
16 [1] 10 40 35 50

The rearrangement
The rearrangement of a vector refers to changing the order of its elements. This can involve sorting the
elements in ascending or descending order, shuffling them randomly, or arranging them based on
specific criteria.
Example:
1 my_vector <- c(3, 1, 4, 1, 5, 9, 2, 6)
2
3 sorted_vector <- sort(my_vector) # Sort the vector in
ascending order
4 print(sorted_vector)
5 [1] 1 1 2 3 4 5 6 9
6
7 sorted_desc_vector <- sort(my_vector, decreasing = TRUE) #Sort the vector in
descending order
8 print(sorted_desc_vector)
9 [1] 9 6 5 4 3 2 1 1
10
11 shuffled_vector <- sample(my_vector, replace = FALSE) # Shuffle the vector
randomly
12 print(shuffled_vector)
13 [1] 1 5 2 4 6 1 3 9
14
15 # Rearrange the vector based on specific criteria # For example, arranging even
numbers before odd numbers
16 sorted_evens_odds <- c(sort(my_vector[my_vector %% 2 == 0]),
sort(my_vector[my_vector %% 2 != 0]))
17 print(sorted_evens_odds)
18 [1] 2 4 6 1 1 3 5 9
19

19
Chapter 2 - Objects, Vectors, and Functions

b) Descriptive statistics on vectors

Fucntion Meaning Example

my_vector <- c(10, 20, 30, 40, 50);


Mean() Compute a mean of a vector
mean(my_vector)

Compute the mdeian of a


Median() median(my_vector)
vector

Compute the Standard


sd() sd(my_vector)
Deviation

var() Compute the Variance var(my_vector)

range() Min and Max values range(my_vector)

quantile() Compute Quantiles quantile(my_vector)

summary() summarizing vectors summary(my_vector)

1.8. Lists
a) Interest of lists
Lists are a highly flexible and widely used data structure in .
A list is a vector whose elements are not necessarily of the same type.
An element of a list is any object, including another list.
The list() function is used to create lists.
Elements of the list are typically accessed by their names (using the $ operator).
1 # Create a list with different types of elements
2 my_list <- list(name = "John", age = 30, scores = c(90, 85, 95), married = TRUE)
3
4 my_list[[1]] # Accesses the first element of the list
5
6 my_list$name # Accesses the element named "name"
7
8 my_list$level<-"Master" # Add an element to a list
9
10 my_list$level=NULL #delete an elemnt by assigning Null value
11
12 my_list <- my_list[-4] #remove the 4 th elemnt

2. Functions in R
2.1. Type of Functions in R
Built-in Functions:
hese are functions that are pre-defined in the R language and are available for immediate use without
the need to load any additional packages. They are part of the base R system and provide basic
functionality for data manipulation, mathematical operations, statistical analysis, etc.

20
Chapter 2 - Objects, Vectors, and Functions

User-defined Functions
These are functions created by users to perform specific tasks that are not already covered by built-in
functions. Users can define their own functions using the function() keyword, specifying the
desired behavior and tasks to be performed by the function.

2.2. help on R for Built-in Functions


1.Using the Help Pane, ? , and help
we can get about a function using :
the Help pane located in the bottom right corner by default
Using the ? Operator ------ -----------example (?mean)
Using the help() Function -----------example help(mean)
Using the example() Function -------example("gamma")

2.3. a user-defined function


Function Definition
To define a user-defined function, you use the function() keyword followed by parentheses
containing the function's arguments, and then curly braces {} containing the code to be executed.
1 my_function <- function(arg1, arg2) {
2 # code to be executed
3}

Example : ( sum function of two numbers )


1 sum1<-function(x,y){
2 return(x+y)
3}
4 sum1(1,2)

Example 2: (function that shows even number in a vector


1 even_num<-function(vec){
2 even <- c()
3 for(num in vec){
4 if (num %% 2 == 0){
5 even <- c(even,num)
6 }
7 }
8 return(even)
9}
10 x<-c(1,2,3)
11 even_num(x)

21
Exercice series III

1. Quiz: N°(1)
Question [solution n°1 p. 35]

1. Perform the following operation: 20000/26.


2. Display the result with only 3 decimals.
Hint:
round()

2. Quiz: N°(2)
Question [solution n°2 p. 35]

1. Create the vector "vec1" containing the sequence of integers from 1 to 12.
2. Append the values 16, 17, 18 to the end of this vector.
Hint:
":", c()

3. Quiz: N°(3)
Question [solution n°3 p. 35]

1. Create the vector "vec2" containing the following values:


1 0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0.

2. Accomplish this task in various ways.


Hint:
seq(), ChatGPT, help()

4. Quiz: N°(4)
Question [solution n°4 p. 36]

1. Create the vector "vec3" containing all multiples of 2 between 2 and 52.
2. Create the vector "vec4" containing the letter A once, the letter B twice, and the letter C three times.
3. What is the length of this sequence?
Hint:
seq(), rep(), c(), length()

22
Exercice series

5. Quiz: N°(5)
Question [solution n°5 p. 36]

Create the vector "vec5" containing the following names:


1 "individual1", "individual2", ..., "individual100"

Hint:
paste(), ChatGPT, help()

6. Quiz: N°(6)
Question [solution n°6 p. 36]

Let:
1 SPE = c("GSI", "ACG", "E-BUSINESS", "DFBM", "MD")

1. Extract the elements from the 1st to the 3rd position


2. Create a new vector SPE2 containing only GSI and DFBM
3. Create a new vector SPE3 containing all specialties except ACG
4. Sort alphabetically
Hint:
Hint: [ ], sort()

7. Quiz: N°(7)
Question [solution n°7 p. 37]

Create, (in a single command line), the vector VE containing the following names:
1 chr1, chr2, ..., chr22, chrX, chrY.

Hint:
paste()

8. Quiz: N°(8)
Question [solution n°8 p. 37]

Let:
1 NOTES = c(15, 20, 5, NA, 12, 10, 8, 16, 18, 6, 3, 20, NA, 14, 9)

1. Find the length of NOTES


2. Compute the mean, minimum, and maximum of NOTES
3. Replace all grades less than 10 with the grade 10
4. Create a new vector NOTES_N that does not contain NA values
Hint:
length(), mean(), min(), max(), [], na.omit.

23
Chapter 3- Mastering R Studio:
Options, Importing, Exporting, and
Packages IV

1. Data Import and Export Management in R


Forms of data
In RStudio, you can import various forms of data, including:
1- Text Files: Such as CSV (comma-separated values), TXT (text), TSV (tab-separated values), etc.

Graphic 6 Example of a CSV data file

Graphic 7 Example of a TXT data file


2- Database Files: SQL databases (using appropriate packages like DBI, RSQLite, etc.)
3- Statistical Software Files: SPSS, SAS, Stata, etc. (using appropriate packages like haven)

24
Chapter 3- Mastering R Studio: Options, Importing, Exporting, and Packages

Importing data into RStudio


1-Using graphical interface:

Graphic 8 Importing data using graphical interface


before importing data you should install required packages

Graphic 9 Installing "readr" package

25
Chapter 3- Mastering R Studio: Options, Importing, Exporting, and Packages

importing a txt file

Graphic 10 step 01

Graphic 11 Step 02

Graphic 12 Step 03

26
Chapter 3- Mastering R Studio: Options, Importing, Exporting, and Packages

Graphic 4 Results of importing a text file


For excel file we should install "readr" and "Rccp" packages and following the same steps.

Graphic 5 importing Excel file

27
Chapter 4: Data Frames (data.frame) V

1. Creating a data.frame
Data Frames are tabular data structures in R.
They can contain a mix of different data types, but each column must have consistent data types.
Create a data frame using the data.frame() function. dd data frame result.png (cf. p.28)
1 # Create a data frame
2 Data_Frame <- data.frame (
3 Name = c("Amin", "Omar", "Aya"),
4 Average = c(10, 15, 12),
5 R_note = c(7, 14, 12)
6)
7
8 # Print the data frame
9 Data_Frame

Graphic 13 Example of data frame on R studio

28
Chapter 4: Data Frames (data.frame)

2. Summarize the Data


Use the summary() function to summarize the data from a Data Frame

Graphic 14 summarize the data from a Data Frame

29
Chapter 4: Data Frames (data.frame)

3. Access Items
you can access items using different ways like :
1 Data_Frame[1]
2 Data_Frame[["Average"]]
3 Data_Frame$R_note

Graphic 15 Example of Accessing Items

4. Add Rows
Use the rbind() function to add new rows in a Data Frame:
Example :
1 # Add a new row
2 New_row_DF <- rbind(Data_Frame, c("Ahmed", 110, 110))
3
4 # Print the new row
5 New_row_DF

30
Chapter 4: Data Frames (data.frame)

Graphic 16 Adding new rows

5. Add Columns
Use the cbind() function to add new columns in a Data Frame:

Graphic 17 Add Columns

31
Chapter 4: Data Frames (data.frame)

6. Remove Rows and Columns


Use the - symbol before the index to remove rows and columns in a Data Frame
Example
1 # Remove a row (e.g., the second row)
2 Data_Frame <- Data_Frame[-2, ]
3
4 # Remove a column (e.g., the "Name" column)
5 Data_Frame <- Data_Frame[, -1]

Graphic 18 Remove Rows

7. Access an element
To access an element in a data frame you can use row and column indices or column names
example
1 # Access element in the third row and "R_note" column
2 element <- Data_Frame[2, "R_note"]

32
Chapter 4: Data Frames (data.frame)

Graphic 19 Access an element

8. Transform variables
The transform() function in R is used to create new variables or modify existing variables in a data
frame
example :
1 # Use the transform() function to add a new variable "Total"
2 Data_Frame <- transform(Data_Frame, Total = R_note + Math )
3
4 # Print the data frame with the new variable "Total"
5 print(Data_Frame)

9. Cross-tabulation
A cross-tabulation is a way to summarize and organize data from a data frame based on two (or more)
variables
example:
1 Data_Frame <- data.frame(
2 Gender = c("Male", "Female", "Male", "Female", "Male"),
3 Specialization = c("GSI", "ACG", "GSI", "GSI", "ACG")
4)
5
6 # Create a cross-tabulation
7 cross_tab <- table(Data_Frame$Gender, Data_Frame$Specialization)
8
9 # Print the cross-tabulation
10 print(cross_tab)

33
Chapter 4: Data Frames (data.frame)

Graphic 20 Cross-tabulation

34
Exercise solutions

[exercice p. 22]
Solution n°1
___________________
Perform the solution directly:
1 20000/26
2 round(20000/26, digits = 3)

___________________
another way is to ; Assign the value "20000/26" to a variable then round that variable:
1 A= 20000/26
2 round(A, digits = 3)

[exercice p. 22]
Solution n°2
1. Créer le vecteur «vec1» contenant la suite des entiers de 1 à 12.
1 vec1 <- 1:12
2 vec1<- (1:12)
3 vec1

2. Ajouter à la fin de ce vecteur les valeurs 16, 17, 18.


1 vec2=c(vec1, 16, 17, 18)
2 vec2

or directly:
1 vec2=c(vec1, 16:18)
2 vec2

[exercice p. 22]
Solution n°3
We can create a sequence using the `seq()` function. Firstly, we observe that the step of the sequence
is 0.5. Therefore, we can generate a sequence with a step of 0.5 in two different ways.
1 seq(0,5,0.5)
2 seq(0, 5, by = 0.5)

Another method involves specifying the length of the vector, with "R" automatically computing the
step (0.5).
Since our vector's length is 11 (indicating 10 steps to be added), and the vector ends with 5, the step is
computed as 5/10 = 0.5.
1 seq(0, 5, length.out = 11)

To obtain help regarding the length.out parameter in the seq() function, you can simply execute
the following code:
1 help(seq)

35
Exercise solutions

[exercice p. 22]
Solution n°4
Perform the solution directly using a sequence by a step of 2:
1 vec3 = seq(2, 52, by = 2)
2 vec3

rep() is used to repeat elements.


So, it repeats the letter "A" once (rep("A", 1)),
the letter "B" twice (rep("B", 2)),
and the letter "C" three times (rep("C", 3)),
and then combines them into a single vector.
1 vec4 = c(rep("A", 1), rep("B", 2), rep("C", 3))
2 vec4
3 length(vec4)

[exercice p. 23]
Solution n°5
We can simply use the paste() function to concatenate elements together.
this function (paste()) will combines the string "individu" with the sequence of integers from 1 to
100.
The sep = " " argument specifies that a space should be used to separate the elements.
1 vec5 = paste("individu", 1:100, sep = " ")
2 vec5

to get help about the past function simply type and compile!
1 ?paste

[exercice p. 23]
Solution n°6
1-Extract the elements from the 1st to the 3rd position
1 SPE =c("GSI", "ACG", "E-BUSINESS", "DFBM", "MD")
2 SPE1=SPE[c(1,3)]
3 SPE1

2-Create a new vector SPE2 containing only GSI and DFBM


1 SPE2=SPE[c(1,4)]
2 SPE2

3-Create a new vector SPE3 containing all specialties except ACG


SPE3=SPE[-2]
SPE3
4-Sort alphabetically
1 sort(SPE)

we can sort it from Z to A


1 sort(SPE,decreasing = TRUE)

36
Exercise solutions

[exercice p. 23]
Solution n°7
1-Without separator ""
1 VE = paste("chr", c(1:22,"X","Y"),sep="")
2 VE

2-Without separator "-"


1 VE1 = paste("chr", c(1:22),"X","Y",sep="-")
2 VE1

[exercice p. 23]
Solution n°8
1-Find the length of NOTES
1 NOTES= c(15, 20, 5, NA, 12, 10, 8, 16, 18, 6, 3, 20, NA, 14, 9)
2 length(NOTES)

2-Compute the mean, minimum, and maximum of NOTES


1 mean(NOTES, na.rm=TRUE)
2 mean(NOTES) #if we don't remove "NA" we got NA
3 min(NOTES, na.rm=TRUE)
4 max(NOTES, na.rm=TRUE)

3-Replace all grades less than 10 with the grade 10


1 NOTES[NOTES < 10] = 10
2 NOTES

4-Create a new vector NOTES_N that does not contain NA values


1 NOTES_N=na.omit(NOTES) #na.omit() est une fonction /#na.rm() est un argument
2 NOTES_N

37
Bibliography

[1] Chitrangada, Chaubey., Anuska, Sharma. (2023). The integrated development environment (IDE) for
application development: Android studio and its tools. Nucleation and Atmospheric Aerosols, doi:
10.1063/5.0116494
[2] V., Narendra, Siva, Kesava., P., Lalitha, Likitha., B., Siva, Sai., K., Praveen., K., Sravani, Bai., G.,
Srinivasa, Rao. (2022). An Online Integrated Development Environment (IDE) by usingLightweight
Framework Render Studio. International Journal of Scientific Research in Computer Science, Engineering
and Information Technology, doi: 10.32628/cseit228386

38
Legal notices

Offered by Dr. Mohamed BOUATELLI & Dr. Rachid AZZAZ at ESGEN1 School, this beginner-level course
focuses on R programming2
-Ownership: All course materials are the intellectual property of Dr. Mohamed BOUATELLI, Dr. Rachid
AZZAZ, and ESGEN School. For inquiries or permission requests, please contact Dr. Mohamed BOUATELLI
and Dr. Rachid AZZAZ or ESGEN School.
Dr. Mohamed BOUATELLI - [email protected]

Dr. Rachid AZZAZ - [email protected] / [email protected]

©ESGEN School 2024

1. https://www.esgen.edu.dz/
2. This course is available in SCORM, Web, and PDF formats at: -

https://elearning.esgen.edu.dz/moodle/course/view.php?id=236

39

You might also like