Thanks to visit codestin.com
Credit goes to www.scribd.com

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

R Programming Basics Guide

Uploaded by

Ammar Jagadhita
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)
8 views39 pages

R Programming Basics Guide

Uploaded by

Ammar Jagadhita
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 Flow Control

R if else Statement

• The syntax of if statement is:

• if else statement
• The syntax of if else statement is:
• Note: The else must be in the same line as the closing braces of the if
statement.
if else Ladder
• The syntax of for this is:

• Only one statement will get executed depending upon the test
expressions.
R switch() Function
• The switch() function in R tests an expression against elements of a list. If
the value evaluated from the expression matches an item from the list, the
corresponding value is returned.

• Here, expression is evaluated and based on this value, the corresponding


item in the list is returned.
• If the value evaluated from expression matches with more than one item of
the list, the switch() function returns the first matched item.
• The expression parameter used in the switch () function can be a string as
well. In this case, the matching named item's value is returned.
R for Loop
• Syntax of for loop

• Here, sequence is a vector and val takes on each of its value during
the loop. In each iteration, statement is evaluated.
R while Loop
• In R programming, while loops are used to loop until a specific condition is
met.

• Here, test_expression is evaluated and the body of the loop is entered if


the result is TRUE.
• The statements inside the loop are executed and the flow returns to
evaluate the test_expression again.
• This is repeated each time until test_expression evaluates to FALSE, in
which case, the loop exits.
R break and next Statement
• In R, the break and next statements are control flow statements used
within loops to control the flow of execution.
break Statement
• A break statement is used inside a loop (repeat, for, while) to stop the
iterations and flow the control outside of the loop.
• In a nested looping situation, where there is a loop inside another
loop, this statement exits from the innermost loop that is being
evaluated.
R break and next Statement
next Statement
• A next statement is useful when we want to skip the current iteration
of a loop without terminating it.
• When the next statement is encountered, the current iteration of the
loop is skipped, and the program moves to the next iteration of the
loop.
R repeat loop
• A repeat loop is used to iterate over a block of code multiple number
of times.
• There is no condition check in repeat loop to exit the loop
• We must ourselves put a condition explicitly inside the body of the
loop and use the break statement to exit the loop. Failing to do so will
result into an infinite loop.
Practice Question
• Check whether a number is an Armstrong number or not.
• An Armstrong number, also known as narcissistic number, is a number that is
equal to the sum of the cubes of its own digits.
• For example, if you have a number like 153, it's an Armstrong number
because 1^3 + 5^3 + 3^3 equals 153.
• E.g. 371 = (3*3*3)+(7*7*7)+(1*1*1)

• Hint: Floor(x)  rounds to the largest integer not greater than x


R Functions
• Functions are used to logically break our code into simpler parts
which become easy to maintain and understand.
• The syntax for writing R function is:

• The statements within the curly braces form the body of the function.
These braces are optional if the body contains only a single
expression.
• Finally, this function object is given a name by assigning it to a
variable, func_name
Named Arguments
• The matching of formal arguments to the actual arguments takes
place in positional order.
• We can also call the function using named arguments.
• When calling a function in this way, the order of the actual arguments
doesn't matter.
Default Values for Arguments
• We can assign default values to arguments in a function in R.
• This is done by providing an appropriate value to the formal argument
in the function declaration.
• The use of default value to an argument makes it optional when
calling the function.
Return Value from Function
• Many times, we will require our functions to do some processing and
return the result. This is accomplished with the return() function in R.
• The syntax of the return() function is:

• Here, expression is evaluated, and its value is stored as the result of


the function.
• The value specified in the return() statement is passed as the output
of the function.
Multiple Returns
• The return() function can return only a single object. If we want to
return multiple values in R, we can use a list (or other objects) and
return it.
Practice Question
• Lets create a function to solve quadratic equations
R Programming Scope
• In R programming, scope refers to the accessibility or visibility of
objects (variables, functions, etc.) within different parts of your code.
• In R, there are two main types of variables: global variables and local
variables.
• Global Variables
• Global variables are those variables which exist throughout the execution of a
program. It can be changed and accessed from any part of the program.
• Local Variables
• Local variables are those variables which exist only within a certain part of a
program like a function, and are released when the function call ends.
R Data Structures
• The base data structures in R are vectors, matrices, arrays, data
frames, and lists.
• The first three, vectors, matrices, and arrays, require all elements to
be of the same type or homogeneous, e.g., all numeric or all
character.
• Data frames and lists allow elements to be of different types or
heterogeneous, e.g., some elements of a data frame may be numeric
while other elements may be character.
• These base structures can also be organized by their dimensionality,
i.e., 1-dimensional, 2-dimensional, or N-dimensional,
Vector
• Vector is a basic data structure in R. It contains elements of the same
type. The data types can be logical, integer, double, character,
complex or raw.
• A vector's type can be checked with the typeof() function.
• Another important property of a vector is its length. This is the
number of elements in the vector and can be checked with the
function length().
How to Create Vector in R
• Vectors are generally created using the c() (combine) function.
• x <- c(1,2,3,4,5)
• x <- 1:7
• seq(1, 3, by=0.2)
• Elements of a vector can be accessed using vector indexing. The
vector used for indexing can be logical, integer or character vector.
• Vector index in R starts from 1
How to modify a vector in R?
• We can modify a vector using the assignment operator.
• If we want to truncate the elements, we can use reassignments.

• How to delete a vector in R?


• We can delete a vector by simply assigning a NULL to it.
Vector Functions
• There are several
functions which can
be used to get
information from
vectors, manipulate
vectors, or inspect
vectors.
Plotting vectors
• One key feature of R is it’s ability to graphically display data (plotting)
R Matrix
• Matrix is a two dimensional data structure in R programming.
• Matrix is similar to vector but additionally contains the dimension
attribute.
• All attributes of an object can be checked with the attributes()
function (dimension can be checked directly with the dim() function).
• A matrix can be created using the matrix() function.
• Dimension of the matrix can be defined by passing appropriate values
for arguments nrow and ncol.
Matrix
• It is possible to name the rows and columns of matrix during creation
by passing a 2 element list to the argument dimnames
• These names can be accessed or changed with two helpful functions
colnames() and rownames().
• Another way of creating a matrix is by using functions cbind() and
rbind() as in column bind and row bind.
• Finally, you can also create a matrix from a vector by setting its
dimension using dim().
How to access Elements of a matrix?
• We can access elements of a matrix using the square bracket []
indexing method.
• Elements can be accessed as var[row, column].
• Here row and column are vectors.
• How to modify a matrix in R?
Transpose a Matrix
• A common operation with matrices is to transpose it. This can be
done with the function t().
Matrix functions
• As for vectors a series of functions exist to work with matrices.
R Lists
• If a vector has elements of different types, it is called a list in R
programming.
• A list is a flexible data structure that can hold elements of different
types, such as numbers, characters, vectors, matrices, and even other
lists.
• We can create a list using the list() function
• The structure of the above list can be examined with the str() function
How to access components of a list?
• Lists can be accessed in similar fashion to vectors.
• Integer, logical or character vectors can be used for indexing.
• Indexing with [ will give us a sublist not the content inside the
component.
• To retrieve the content, we need to use [[.
• An alternative to [[, which is used often while accessing content of a
list is the $ operator.
How to modify a list in R?
• We can change components of a list through reassignment.
• We can choose any of the component accessing techniques discussed
before to modify it.
• How to add components to a list?
• Assign values using new tags and it will pop into action.
• How to delete components from a list?
• We can delete a component by assigning NULL to it.
R Data Frame
• Data frame is a two dimensional data structure in R.
• It is a special case of a list which has each component of equal length.
• Each component forms the column and contents of the component
form the rows.
• We can create a data frame using the data.frame() function.
• Many data input functions of R like, read.table(), read.csv(),
read.delim(), read.fwf() also read data into a data frame  we will
talk later
How to Access Components of a Data Frame?
• Components of the data frame can be accessed like a list or like a
matrix
• We can use either [, [[ or $ operator to access columns of data frame.
• How to modify a Data Frame in R?
• Data frames can be modified like we modified matrices through
reassignment.
• Adding Components to Data Frame
• Rows can be added to a data frame using the rbind() function.
R Factors
• Factor is a data structure used for fields that takes only a predefined,
finite number of values (categorical data).
• For example: a data field such as marital status may contain only values from
single, married, separated, divorced, or widowed.
• In such a case, we know the possible values beforehand and these
predefined, distinct values are called levels.
• We can create a factor using the function factor()
Practice
• Write a R program to create two 2x3 matrix and add, subtract,
multiply and divide the matrixes.
• Write a R program to calculate row sums of a matrix using loops
• Write a R program to calculate row sums of a data frame using loops
Practice
• 1- Create the following data frame:
43 181 M
• mydf: 34 172 F
22 189 M
27 167 F

• With Row names: John, Jessica, Steve, Rachel.


And Column names: Age, Height, Gender
Practice
• Calculate the average age and height in mydf
• Add one row to mydf: Georges who is 53 years old and 168cm tall.
• Change the row names of mydf so the data becomes
anonymous: Use Patient1, Patient2, etc. instead of actual names.
• Create the data frame mydf2 that is a subset of mydf containing
only the female entries.
• Create the data frame mydf3 that is a subset of mydf containing
only entries of males taller than 170.
Practice
• download.file("https://public-
docs.crg.es/biocore/sbonnin/Rcourse/genes_dataframe.RData",
"genes_dataframe.RData")
• Load genes_dataframe.RData in your environment Use the load function.
• Explore data and see what it contains
• change column names
• Select rows for which pvalue_KOvsWT (C3) < 0.05 AND
log2FoldChange_KOvsWT(C2) > 0.5. Store in another object.
• Select from the up object the Zinc finger protein coding genes (i.e. the gene
symbol starts with Zfp  to do this you need to learn grep function. Use
help to learn about it

You might also like