You are on page 1of 11

COURSE ON R Programming

Presented by: Adarsh Godia

(Division Mathematics, UIS)

Provisional Registration Number: Supervisor(s): Dr. Nishi Gupta


22MSM40206 (Associate Professor)
Division Mathematics, UIS

Division Mathematics, UIS Adarsh 1


What is R Programming ?
• R is a programming language and also a software environment for statistical computing and data
analysis.
• R was developed by Ross Ihaka and Robert Gentleman.
• R is an open-source programming language and it is available on widely used platforms e.g.
Windows, Linux, and Mac.
• It generally comes with a command-line interface and provides a vast list of packages for
performing tasks.
• R is an interpreted language that supports both procedural programming and object-oriented
programming.

Syntax of R program
• A program in R is made up of three things: Variables, Comments, and Keywords. Variables are used to store
the data, Comments are used to improve code readability, and Keywords are reserved words that hold a
specific meaning to the compiler.

Division Mathematics, UIS Adarsh 2


What are R Data types?

• R Data types are used in computer programming to specify the kind of data that can be stored in a variable. For
effective memory consumption and precise computation, the right data type must be selected. Each R data type has
its own set of regulations and restrictions.

Division Mathematics, UIS Adarsh 3


Control structures and functions in R
Language
• Control structures in R allow you to control the flow of execution of a series of R expressions. They are used to
make decisions, repeat code, and skip code.

• The following are the most common control structures in R:

• If-else statement: The if-else statement is used to test a condition and execute different code depending on whether
the condition is true or false.
• For loop: The for loop is used to iterate over a sequence of values.
• While loop: The while loop is used to repeatedly execute a block of code until a condition is met.
• Repeat loop: The repeat loop is similar to the while loop, but it does not have a condition. The repeat loop will
continue to execute until a break statement is encountered.
• Next statement: The next statement is used to skip the current iteration of a loop.
• Break statement: The break statement is used to terminate a loop.
• Functions are a way to group together related code so that it can be reused. They are also used to abstract away
complex code, making it easier to read and understand.

• The following are the basic components of a function in R:


• The function name: This is the name that is used to call the function.
• The function arguments: These are the values that are passed to the function when it is called.
• The function body: This is the code that is executed when the function is called.
• To define a function in R, you use the function() keyword. The syntax is as follows:

Division Mathematics, UIS Adarsh 4


The scoping rules in R
• determine how the values of variables are determined. There are two types of scopes in R:
• Local scope: This is the scope of a variable within a function. The values of variables in the local scope are only visible within the function.
• Global scope: This is the scope of a variable outside of any function. The values of variables in the global scope are visible to all functions.
• When a variable is used in a function, the R interpreter first looks for the variable in the local scope. If the variable is not found in the local
scope, the interpreter then looks for the variable in the global scope.

• If the variable is still not found, the interpreter will generate an error.
• Here is an example of how scoping works in R:
• x <- 10 # This defines x in the global scope
• f <- function(){
• y <- 20 # This defines y in the local scope of f
• print(x) # This will print the value of x from the global scope
• }
• f() # This calls the function f
• In this example, the value of x that is printed is 10, which is the value of x in the global scope. The value of y is not visible outside of the
function f.

• Here are some additional things to keep in mind about scoping in R:

• The environment of a function is the collection of all variables that are visible to the function. The environment of a function is created when the
function is defined.
• When a function is called, the environment of the function is created as a child of the environment in which the function was called.
• This means that the variables in the environment in which the function was called are also visible to the function.
• This is called lexical scoping, and it is the default scoping mechanism in R.

Division Mathematics, UIS Adarsh 5


Lexical Scoping in R programming
• means that the values of the free variables are searched for in the environment in which the function was defined. An environment is a collection of
symbols, value, and pair, every ePrinciples of Lexical Scoping
• There are four basic principles behind R’s implementation of lexical scoping:
• Name Masking
• Functions vs variables
• A fresh start
• Dynamic Lookup
• nvironment has a parent environment
• Name Masking
• The following example illustrates the most basic principle of lexical scoping, and you should have no problem predicting the output.
• If variable is not defined inside the function:
• Example:
• c <- 10
• f <- function(a, b)
• {
• a+b+c
• }
• f(8, 5)
• Output: 23
• It takes the c value as 10 and then adds these numbers and finally we are having 23 as output.
• If name is not defined inside the function:
• If a name isn’t defined inside a function, R will look one level up.
• Example:
• a <- 10
• b <- function()
• {
• c <- 11
• c(a, c)
• }
• b()
• Output: 10 11
DIVISION MATHEMATICS,UIS Adarsh 6
Lexical Scoping in R programming
• Functions vs Variables
• The same principles apply regardless of the type of associated value — finding functions works exactly the same way as finding variables:
• Example:
• a <- function(x) 10 * x
• b <- function(){
• a <- function(x) x + 10
• a(12)
• }
• b()
• Output: 22

• A Fresh Start
• When a function is called, a new environment is created every time. Each acknowledgement is completely independent because a function cannot tell
what happened when it was run last time.
• Example:
• a <- function(){
• if(!exists("z"))
• {
• z <- 10
• }
• else
• {
• z <- z+10
• }
• z
• }
• a()
• Output:10

DIVISION MATHEMATICS , UIS Adarsh 7


Dynamic Lookup
Lexical scoping controls where to look for values not when to look for them. R looks for the values when the function is executed not
when it is created. The output of the function can be different depending on objects outside its environment.
Example:
g <- function() x^3
x <- 10
g()
Output: 1000

There is a function in R which is findGlobals() from codetools and it helps us to find all global variables being used in a function and
lists all the external dependencies of a function. findGlobals() find the global variables and functions which are used by the closure.

Example:
aGlobal <- rnorm(10)
bGlobal <- rnorm(10)

f <- function()
{
a <- aGlobal
b <- bGlobal
plot(b ~ a)
}
codetools::findGlobals(f)
Output:
"{" "~" "<-" "aGlobal" "bGlobal" "plot“

We can manually change the environment to the empty environment emptyenv(). emptyenv() is a totally empty environment.

Division Mathematics, UIS Adarsh 8


ProgrammingAssignment: Caching the
Inverse of a Matrix
• Caching the inverse of a matrix is a technique that can be used to speed up computations that involve repeatedly inverting the
same matrix. The basic idea is to store the inverse of the matrix in a cache, so that it can be retrieved quickly when needed.
This can be done by using two functions:

• makeCacheMatrix(): This function creates a special "matrix" object that can cache its inverse.
• cacheSolve(): This function computes the inverse of the special "matrix" object returned by makeCacheMatrix(). If the
inverse has already been calculated (and the matrix has not changed), then cacheSolve() should retrieve the inverse from the
cache.

Division Mathematics, UIS Adarsh 9


Code and its functions

makeCacheMatrix <- function(matrix) { #function after running the code


inv <- NULL
>matrix <- matrix(c(4, 7, 2, 6), nrow = 2)
set <- function(newValue) { > cacheMatrix <- makeCacheMatrix(matrix)
matrix <<- newValue > inverse <- cacheSolve(cacheMatrix)
inv <<- NULL # Reset cached inverse >print(inverse)
}
[,1] [,2]
get <- function() { [1,] 0.6 -0.2
matrix [2,] -0.7 0.4
}
> cachedInverse <- cacheSolve(cacheMatrix)
cacheInverse <- function() { Getting cached inverse
if (!is.null(inv)) {
message("Getting cached inverse") > print(inverse)
return(inv) [,1] [,2]
} [1,] 0.6 -0.2
[2,] -0.7 0.4
inv <<- solve(matrix)
inv
}

list(set = set, get = get, cacheInverse = cacheInverse)


}
cacheSolve <- function(cacheMatrix) {
if (!is.function(cacheMatrix$cacheInverse)) {
stop("Input must be a cacheMatrix object.")
}

cacheMatrix$cacheInverse()

Division Mathematics, UIS Adarsh 10


• Thank You

Division Mathematics, UIS Adarsh 11

You might also like