0% found this document useful (0 votes)
4 views

r Programming Unit-2

This document provides an overview of control flow statements in R programming, focusing on the if, if-else, else if, and switch statements. It includes syntax explanations, flow charts, and multiple examples demonstrating how these statements are used to make decisions based on Boolean expressions. Additionally, it covers the next statement, which allows skipping iterations in loops.

Uploaded by

anandmkattimani
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)
4 views

r Programming Unit-2

This document provides an overview of control flow statements in R programming, focusing on the if, if-else, else if, and switch statements. It includes syntax explanations, flow charts, and multiple examples demonstrating how these statements are used to make decisions based on Boolean expressions. Additionally, it covers the next statement, which allows skipping iterations in loops.

Uploaded by

anandmkattimani
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/ 72

R PROGRAMMING

UNIT – 2
R if Statement
The if statement consists of the Boolean expressions followed by one or more statements. The if
statement is the simplest decision-making statement which helps us to take a decision on the basis
of the condition.

The if statement is a conditional programming statement which performs the function and displays
the information if it is proved true.

The block of code inside the if statement will be executed only when the boolean expression
evaluates to be true. If the statement evaluates false, then the code which is mentioned after the
condition will run.

The syntax of if statement in R is as follows:

1. if(boolean_expression) {
2. // If the boolean expression is true, then statement(s) will be executed.
3. }

Flow Chart
R PROGRAMMING

Let see some examples to understand how if statements work and perform a certain task in R.

Example 1

1. x <-24L
2. y <- "shubham"
3. if(is.integer(x))
4. {
5. print("x is an Integer")
6. }

Output:

Example 2

1. x <-20
2. y<-24
3. count=0
4. if(x<y)
5. {
6. cat(x,"is a smaller number\n")
7. count=1
8. }
9. if(count==1){
10. cat("Block is successfully execute")
11. }

Output:
R PROGRAMMING

Example 3

1. x <-1
2. y<-24
3. count=0
4. while(x<y){
5. cat(x,"is a smaller number\n")
6. x=x+2
7. if(x==15)
8. break
9. }

Output:

Example 4

1. x <-24
2. if(x%%2==0){
3. cat(x," is an even number")
R PROGRAMMING

4. }
5. if(x%%2!=0){
6. cat(x," is an odd number")
7. }

Output:

Example 5

1. year
2. 1 = 2011
3. if(year1 %% 4 == 0) {
4. if(year1 %% 100 == 0) {
5. if(year1 %% 400 == 0) {
6. cat(year,"is a leap year")
7. } else {
8. cat(year,"is not a leap year")
9. }
10. } else {
11. cat(year,"is a leap year")
12. }
13. } else {
14. cat(year,"is not a leap year")
15. }

Output:
R PROGRAMMING

If-else statement
In the if statement, the inner code is executed when the condition is true. The code which is outside
the if block will be executed when the if condition is false.

There is another type of decision-making statement known as the if-else statement. An if-else
statement is the if statement followed by an else statement. An if-else statement, else statement
will be executed when the boolean expression will false. In simple words, If a Boolean expression
will have true value, then the if block gets executed otherwise, the else block will get executed.

R programming treats any non-zero and non-null values as true, and if the value is either zero or
null, then it treats them as false.

The basic syntax of If-else statement is as follows:

1. if(boolean_expression) {
2. // statement(s) will be executed if the boolean expression is true.
3. } else {
4. // statement(s) will be executed if the boolean expression is false.
5. }

Flow Chart
R PROGRAMMING

Example 1

1. # local variable definition


2. a<- 100
3. #checking boolean condition
4. if(a<20){
5. # if the condition is true then print the following
6. cat("a is less than 20\n")
7. }else{
8. # if the condition is false then print the following
9. cat("a is not less than 20\n")
10. }
11. cat("The value of a is", a)
R PROGRAMMING

Output:

Example 2

1. x <- c("Hardwork","is","the","key","of","success")
2.
3. if("key" %in% x) {
4. print("key is found")
5. } else {
6. print("key is not found")
7. }

Output:

Example 3

1. a<- 100
2. #checking boolean condition
3. if(a<20){
4. cat("a is less than 20")
5. if(a%%2==0){
6. cat(" and an even number\n")
7. }
8. else{
9. cat(" but not an even number\n")
10. }
11. }else{
R PROGRAMMING

12. cat("a is greater than 20")


13. if(a%%2==0){
14. cat(" and an even number\n")
15. }
16. else{
17. cat(" but not an even number\n")
18. }
19. }

Output:

Example 4

1. a<- 'u'
2. if(a=='a'||a=='e'||a=='i'||a=='o'||a=='u'||a=='A'||a=='E'||a=='I'||a=='O'||a=='U'){
3. cat("character is a vowel\n")
4. }else{
5. cat("character is a constant")
6. }
7. cat("character is =",a)
8. }

Output:
R PROGRAMMING

Example 5

1. a<- 'u'
2. if(a=='a'||a=='e'||a=='i'||a=='o'||a=='u'||a=='A'||a=='E'||a=='I'||a=='O'||a=='U'){
3. cat("character is a vowel\n")
4. }else{
5. cat("character is a constant")
6. }
7. cat("character is =",a)
8. }

Output:

R else if statement
This statement is also known as nested if-else statement. The if statement is followed by an
optional else if..... else statement. This statement is used to test various condition in a single
if. else if statement. There are some key points which are necessary to keep in mind when we
are using the if.....else if. else statement. These points are as follows:
R PROGRAMMING

1. if statement can have either zero or one else statement and it must come after any else
if's statement.
2. if statement can have many else if's statement and they come before the else statement.
3. Once an else if statement succeeds, none of the remaining else if's or else's will be tested.

The basic syntax of If-else statement is as follows:

1. if(boolean_expression 1) {
2. // This block executes when the boolean expression 1 is true.
3. } else if( boolean_expression 2) {
4. // This block executes when the boolean expression 2 is true.
5. } else if( boolean_expression 3) {
6. // This block executes when the boolean expression 3 is true.
7. } else {
8. // This block executes when none of the above condition is true.
9. }

Flow Chart
R PROGRAMMING

Example 1

1. age <- readline(prompt="Enter age: ")


2. age <- as.integer(age)
3. if(age<18)
R PROGRAMMING

4. print("You are child")


5. else if(age>30)
6. print("You are old guy")
7. else
8. print("You are adult")

Output:

Example 2

1. marks=83;
2. if(marks>75){
3. print("First class")
4. }else if(marks>65){
5. print("Second class")
6. }else if(marks>55){
7. print("Third class")
8. }else{
9. print("Fail")
10. }

Output:
R PROGRAMMING

Example 3

1. cat("1) For Addition\n")


2. cat("2) For Subtraction\n")
3. cat("3) For Division\n")
4. cat("4) For multiplication\n")
5. n1<-readline(prompt="Enter first number:")
6. n2<-readline(prompt="Enter second number:")
7. choice<-readline(prompt="Enter your choice:")
8. n1<- as.integer(n1)
9. n2<- as.integer(n2)
10. choice<- as.integer(choice)
11. if(choice==1){
12. sum <-(n1+n2)
13. cat("sum=",sum)
14. }else if(choice==2){
15. sub<-(n1-n2)
16. cat("sub=",sub)
17. }else if(choice==3){
18. div<-n1/n2
19. cat("Division=",div)
R PROGRAMMING

20. }else if(choice==4){


21. mul<-n1*n2
22. cat("mul=",mul)
23. }else{
24. cat("wrong choice")
25. }

Output:

Example 4

1. x <- c("Hardwork","is","the","key","of","success")
2. if("Success" %in% x) {
3. print("success is found in the first time")
4. } else if ("success" %in% x) {
5. print("success is found in the second time")
6. } else {
7. print("No success found")
8. }

Output:
R PROGRAMMING

Example 5

1. n1=4
2. n2=87
3. n3=43
4. n4=74
5. if(n1>n2){
6. if(n1>n3&&n1>n4){
7. largest=n1
8. }
9. }else if(n2>n3){
10. if(n2>n1&&n2>n4){
11. largest=n2
12. }
13. }else if(n3>n4){
14. if(n3>n1&&n3>n2){
15. largest=n3
16. }
17. }else{
18. largest=n4
19. }
20. cat("Largest number is =",largest)

Output:
R PROGRAMMING

R Switch Statement
A switch statement is a selection control mechanism that allows the value of an expression to
change the control flow of program execution via map and search.

The switch statement is used in place of long if statements which compare a variable with several
integral values. It is a multi-way branch statement which provides an easy way to dispatch
execution for different parts of code. This code is based on the value of the expression.

This statement allows a variable to be tested for equality against a list of values. A switch statement
is a little bit complicated. To understand it, we have some key points which are as follows:

o If expression type is a character string, the string is matched to the listed cases.
o If there is more than one match, the first match element is used.
o No default case is available.
o If no case is matched, an unnamed case is used.

There are basically two ways in which one of the cases is selected:

1) Based on Index
If the cases are values like a character vector, and the expression is evaluated to a number than the
expression's result is used as an index to select the case.

2) Based on Matching Value


When the cases have both case value and output value like ["case_1"="value1"], then the
expression value is matched against case values. If there is a match with the case, the corresponding
value is the output.

The basic syntax of If-else statement is as follows:

1. switch(expression, case1, case2, case3. .. )

Flow Chart
R PROGRAMMING

Example 1

1. x <- switch(
2. 3,
3. "Shubham",
4. "Nishka",
5. "Gunjan",
6. "Sumit"
7. )
8. print(x)
R PROGRAMMING

Output:

Example 2

1. ax= 1
2. bx = 2
3. y = switch(
4. ax+bx,
5. "Hello, Shubham",
6. "Hello Arpita",
7. "Hello Vaishali",
8. "Hello Nishka"
9. )
10. print (y)

Output:

Example 3

1. y = "18"
2. x = switch(
3. y,
4. "9"="Hello Arpita",
R PROGRAMMING

5. "12"="Hello Vaishali",
6. "18"="Hello Nishka",
7. "21"="Hello Shubham"
8. )
9.
10. print (x)

Output:

Example 4

1. x= "2"
2. y="1"
3. a = switch(
4. paste(x,y,sep=""),
5. "9"="Hello Arpita",
6. "12"="Hello Vaishali",
7. "18"="Hello Nishka",
8. "21"="Hello Shubham"
9. )
10.
11. print (a)

Output:
R PROGRAMMING

Example 5

1. y = "18"
2. a=10
3. b=2
4. x = switch(
5. y,
6. "9"=cat("Addition=",a+b),
7. "12"=cat("Subtraction =",a-b),
8. "18"=cat("Division= ",a/b),
9. "21"=cat("multiplication =",a*b)
10. )
11.
12. print (x)

Output:

R next Statement
The next statement is used to skip any remaining statements in the loop and continue executing.
In simple words, a next statement is a statement which skips the current iteration of a loop without
terminating it. When the next statement is encountered, the R parser skips further evaluation and
starts the next iteration of the loop.
R PROGRAMMING

This statement is mostly used with for loop and while loop.

Note: In else branch of the if-else statement, the next statement can also be used.

Syntax
There is the following syntax for creating the next statement in R

1. next

Flowchart

Example 1: next in repeat loop

1. a <- 1
2. repeat {
3. if(a == 10)
4. break
5. if(a == 5){
R PROGRAMMING

6. next
7. }
8. print(a)
9. a <- a+1
10. }

Output:

Example 2: next in while loop

1. a<-1
2. while (a < 10) {
3. if(a==5)
4. next
5. print(a)
6. a=a+1
7. }

Output:
R PROGRAMMING

Example 3: next in for loop

1. x <- 1:10
2. for (val in x) {
3. if (val == 3){
4. next
5. }
6. print(val)
7. }

Output:

Example 4

1. a1<- c(10L,-11L,12L,-13L,14L,-15L,16L,-17L,18L)
2. sum<-0
3. for(i in a1){
4. if(i<0){
5. next
6. }
7. sum=sum+i
8. }
9. cat("The sum of all positive numbers in array is=",sum)
R PROGRAMMING

Output:

Example 5

1. j<-0
2. while(j<10){
3. if (j==7){
4. j=j+1
5. next
6. }
7. cat("\nnumber is =",j)
8. j=j+1
9. }

Output:

R Break Statement
R PROGRAMMING

In the R language, the break statement is used to break the execution and for an immediate exit
from the loop. In nested loops, break exits from the innermost loop only and control transfer to the
outer loop.

It is useful to manage and control the program execution flow. We can use it to various loops like:
for, repeat, etc.

There are basically two usages of break statement which are as follows:

1. When the break statement is inside the loop, the loop terminates immediately and program control
resumes on the next statement after the loop.
2. It is also used to terminate a case in the switch statement.

Note: We can also use break statement inside the else branch of if...else statement.

Syntax
There is the following syntax for creating a break statement in R

Backward Skip 10sPlay VideoForward Skip 10s

1. break

Flowchart
R PROGRAMMING

Example 1: Break in repeat loop

1. a <- 1
2. repeat {
3. print("hello");
4. if(a >= 5)
5. break
6. a<-a+1
7. }

Output:

Example 2

1. v <- c("Hello","loop")
2. count <- 2
3. repeat {
4. print(v)
5. count <- count + 1
6. if(count > 5) {
7. break
8. }
9. }

Output:
R PROGRAMMING

Example 3: Break in while loop

1. a<-1
2. while (a < 10) {
3. print(a)
4. if(a==5)
5. break
6. a=a+1
7. }

Output:

Example 4: Break in for loop

1. for (i in c(2,4,6,8)) {
2. for (j in c(1,3)) {
3. if (i==6)
R PROGRAMMING

4. break
5. print(i)
6. }
7. }

Output:

Example 5

1. num=7
2. flag = 0
3. if(num> 1) {
4. flag = 1
5. for(i in 2:(num-1)) {
6. if ((num %% i) == 0) {
7. flag = 0
8. break
9. }
10. }
11. }
12. if(num == 2) flag = 1
13. if(flag == 1) {
14. print(paste(num,"is a prime number"))
15. } else {
16. print(paste(num,"is not a prime number"))
17. }
R PROGRAMMING

Output:

R For Loop
A for loop is the most popular control flow statement. A for loop is used to iterate a vector. It is
similar to the while loop. There is only one difference between for and while, i.e., in while loop,
the condition is checked before the execution of the body, but in for loop condition is checked after
the execution of the body.

There is the following syntax of For loop in C/C++:

1. for (initialization_Statement; test_Expression; update_Statement)


2. {
3. // statements inside the body of the loop
4. }

How For loop works in C/C++?


The for loop in C and C++ is executed in the following way:

o The initialization statement of for loop is executed only once.


o After the initialization process, the test expression is evaluated. The for loop is terminated when
the test expression is evaluated to false.
o The statements inside the body of for loop are executed, and expression is updated if the test
expression is evaluated to true.

o The test expression is again evaluated.


o The process continues until the test expression is false. The loop terminates when the test
expression is false.
R PROGRAMMING

For loop in R Programming


In R, a for loop is a way to repeat a sequence of instructions under certain conditions. It allows us
to automate parts of our code which need repetition. In simple words, a for loop is a repetition
control structure. It allows us to efficiently write the loop that needs to execute a certain number
of time.

In R, a for loop is defined as :

1. It starts with the keyword for like C or C++.


2. Instead of initializing and declaring a loop counter variable, we declare a variable which is of the
same type as the base type of the vector, matrix, etc., followed by a colon, which is then followed
by the array or matrix name.
3. In the loop body, use the loop variable rather than using the indexed array element.
4. There is a following syntax of for loop in R:

1. for (value in vector) {


2. statements
3. }

Flowchart
R PROGRAMMING

Example 1: We iterate all the elements of a vector and print the current value.

1. # Create fruit vector


2. fruit <- c('Apple', 'Orange',"Guava", 'Pinapple', 'Banana','Grapes')
3. # Create the for statement
4. for ( i in fruit){
5. print(i)
6. }

Output
R PROGRAMMING

Example 2: creates a non-linear function with the help of the polynomial of x between 1 and 5
and store it in a list.

1. # Creating an empty list


2. list <- c()
3. # Creating a for statement to populate the list
4. for (i in seq(1, 5, by=1)) {
5. list[[i]] <- i*i
6. }
7. print(list)

Output

Example 3: For loop over a matrix

1. # Creating a matrix
2. mat <- matrix(data = seq(10, 21, by=1), nrow = 6, ncol =2)
R PROGRAMMING

3. # Creating the loop with r and c to iterate over the matrix


4. for (r in 1:nrow(mat))
5. for (c in 1:ncol(mat))
6. print(paste("mat[", r, ",",c, "]=", mat[r,c]))
7. print(mat)

Output

Example 4: For loop over a list

1. # Create a list with three vectors


2. fruit <- list(Basket = c('Apple', 'Orange',"Guava", 'Pinapple', 'Banana','Grapes'),
3. Money = c(10, 12, 15), purchase = TRUE)
4. for (p in fruit)
5. {
6. print(p)
7. }
R PROGRAMMING

Output

Example 5: count the number of even numbers in a vector.# Create a list with three vectors.

1. x <- c(2,5,3,9,8,11,6,44,43,47,67,95,33,65,12,45,12)
2. count <- 0
3. for (val in x) {
4. if(val %% 2 == 0) count = count+1
5. }
6. print(count)

Output

R repeat loop
A repeat loop is used to iterate a block of code. It is a special type of loop in which there is no
condition to exit from the loop. For exiting, we include a break statement with a user-defined
condition. This property of the loop makes it different from the other loops.

A repeat loop constructs with the help of the repeat keyword in R. It is very easy to construct an
infinite loop in R.
R PROGRAMMING

The basic syntax of the repeat loop is as follows:

1. repeat {
2. commands
3. if(condition) {
4. break
5. }
6. }

Flowchart

1. First, we have to initialize our variables than it will enter into the Repeat loop.
2. This loop will execute the group of statements inside the loop.
3. After that, we have to use any expression inside the loop to exit.
4. It will check for the condition. It will execute a break statement to exit from the loop
5. If the condition is true.
6. The statements inside the repeat loop will be executed again if the condition is false.

Example 1:

1. v <- c("Hello","repeat","loop")
2. cnt <- 2
R PROGRAMMING

3. repeat {
4. print(v)
5. cnt <- cnt+1
6.
7. if(cnt > 5) {
8. break
9. }
10. }

Output

Example 2:

1. sum <- 0
2. {
3. n1<-readline(prompt="Enter any integer value below 20: " )
4. n1<-as.integer(n1)
5. }
6. repeat{
7. sum<-sum+n1
8. n1n1=n1+1
9. if(n1>20){
10. break
11. }
12. }
13. cat("The sum of numbers from the repeat loop is: ",sum)
R PROGRAMMING

Output

Example 3: Infinity repeat loop

1. total<-0
2. number<-readline(prompt="please enter any integer value: ")
3. repeat{
4. totaltotal=total+number
5. numbernumber=number+1
6. cat("sum is =",total)
7. }

Output
R PROGRAMMING

Example 4: repeat loop with next

1. a <- 1
2. repeat {
3. if(a == 10)
4. break
5. if(a == 7){
6. aa=a+1
7. next
8. }
9. print(a)
10. a <- a+1
11. }

Output
R PROGRAMMING

Example 5:

1. terms<-readline(prompt="How many terms do you want ?")


2. terms<-as.integer(terms)
3. i<-1
4. repeat{
5. print(paste("The cube of number",i,"is =",(i*i*i)))
6. if(i==terms)
7. break
8. i<-i+1
9. }

Output
R PROGRAMMING

R while loop
A while loop is a type of control flow statements which is used to iterate a block of code several
numbers of times. The while loop terminates when the value of the Boolean expression will be
false.

In while loop, firstly the condition will be checked and then after the body of the statement will
execute. In this statement, the condition will be checked n+1 time, rather than n times.

The basic syntax of while loop is as follows:

1. while (test_expression) {
2. statement
3. }

Flowchart
R PROGRAMMING

Example 1:

1. v <- c("Hello","while loop","example")


2. cnt <- 2
3. while (cnt < 7) {
4. print(v)
5. cntcnt = cnt + 1
6. }}

Output
R PROGRAMMING

Example 2: Program to find the sum of the digits of the number.

1. n<-readline(prompt="please enter any integer value: ")


2. please enter any integer value: 12367906
3. n <- as.integer(n)
4. sum<-0
5. while(n!=0){
6. sumsum=sum+(n%%10)
7. n=as.integer(n/10)
8. }
9. cat("sum of the digits of the numbers is=",sum)

Output

Example 3: Program to check a number is palindrome or not.


R PROGRAMMING

1. n <- readline(prompt="Enter a four digit number please: ")


2. n <- as.integer(n)
3. num<-n
4. rev<-0
5. while(n!=0){
6. rem<-n%%10
7. rev<-rem+(rev*10)
8. n<-as.integer(n/10)
9. }
10. print(rev)
11. if(rev==num){
12. cat(num,"is a palindrome num")
13. }else{
14. cat(num,"is not a palindrome number")
15. }

Output

Example 4: Program to check a number is Armstrong or not.

1. num = as.integer(readline(prompt="Enter a number: "))


R PROGRAMMING

2. sum = 0
3. temp = num
4. while(temp > 0) {
5. digit = temp %% 10
6. sumsum = sum + (digit ^ 3)
7. temp = floor(temp / 10)
8. }
9. if(num == sum) {
10. print(paste(num, "is an Armstrong number"))
11. } else {
12. print(paste(num, "is not an Armstrong number"))
13. }

Output

Example 5: program to find the frequency of a digit in the number.

1. num = as.integer(readline(prompt="Enter a number: "))


2. digit = as.integer(readline(prompt="Enter digit: "))
3. n=num
4. count = 0
5. while(num > 0) {
R PROGRAMMING

6. if(num%%10==digit){
7. countcount=count+18.
}
9. num=as.integer(num/10)
10. }
11. print(paste("The frequency of",digit,"in",n,"is=",count))

Output

R Functions
A set of statements which are organized together to perform a specific task is known as a function.
R provides a series of in-built functions, and it allows the user to create their own functions.
Functions are used to perform tasks in the modular approach.

Functions are used to avoid repeating the same task and to reduce complexity. To understand and
maintain our code, we logically break it into smaller parts using the function. A function should
be

1. Written to carry out a specified task.


2. May or may not have arguments
3. Contain a body in which our code is written.
4. May or may not return one or more output values.
R PROGRAMMING

"An R function is created by using the keyword function." There is the following syntax of R
function:

1. func_name <- function(arg_1, arg_2, ...) {


2. Function body
3. }

Components of Functions
There are four components of function, which are as follows:

Function Name

The function name is the actual name of the function. In R, the function is stored as an object with
its name.

Arguments

In R, an argument is a placeholder. In function, arguments are optional means a function may or


may not contain arguments, and these arguments can have default values also. We pass a value to
the argument when a function is invoked.

Function Body
R PROGRAMMING

The function body contains a set of statements which defines what the function does.

Return value

It is the last expression in the function body which is to be evaluated.

Function Types
Similar to the other languages, R also has two types of function, i.e. Built-in Function and User-
defined Function. In R, there are lots of built-in functions which we can directly call in the
program without defining them. R also allows us to create our own functions.

Built-in function
The functions which are already created or defined in the programming framework are known as
built-in functions. User doesn't need to create these types of functions, and these functions are built
into an application. End-users can access these functions by simply calling it. R have different
types of built-in functions such as seq(), mean(), max(), and sum(x) etc.

1. # Creating sequence of numbers from 32 to 46.


2. print(seq(32,46))
3.
4. # Finding the mean of numbers from 22 to 80.
5. print(mean(22:80))
6.
7. # Finding the sum of numbers from 41 to 70.
R PROGRAMMING

8. print(sum(41:70))

Output:

User-defined function
R allows us to create our own function in our program. A user defines a user-define function to
fulfill the requirement of user. Once these functions are created, we can use these functions like
in-built function.

1. # Creating a function without an argument.


2. new.function <- function() {
3. for(i in 1:5) {
4. print(i^2)
5. }
6. }
7.
8. new.function()

Output:
R PROGRAMMING

Function calling with an argument


We can easily call a function by passing an appropriate argument in the function. Let see an
example to see how a function is called.

1. # Creating a function to print squares of numbers in sequence.


2. new.function <- function(a) {
3. for(i in 1:a) {
4. b <- i^2
5. print(b)
6. }
7.
8. # Calling the function new.function supplying 10 as an argument.
9. new.function(10)

Output:

Function calling with no argument


In R, we can call a function without an argument in the following way

1. # Creating a function to print squares of numbers in sequence.


R PROGRAMMING

2. new.function <- function() {


3. for(i in 1:5) {
4. a <- i^2
5. print(a)
6. }
7. }
8.
9. # Calling the function new.function with no argument.
10. new.function()

Output:

Function calling with Argument Values


We can supply the arguments to a function call in the same sequence as defined in the function or
can supply in a different sequence but assigned them to the names of the arguments.

1. # Creating a function with arguments.


2. new.function <- function(x,y,z) {
3. result <- x * y + z
4. print(result)
5. }
6.
7. # Calling the function by position of arguments.
8. new.function(11,13,9)
9.
10. # Calling the function by names of the arguments.
R PROGRAMMING

11. new.function(x = 2, y = 5, z = 3)

Output:

Function calling with default arguments


To get the default result, we assign the value to the arguments in the function definition, and then
we call the function without supplying argument. If we pass any argument in the function call,
then it will get replaced with the default value of the argument in the function definition.

1. # Creating a function with arguments.


2. new.function <- function(x = 11, y = 24) {
3. result <- x * y
4. print(result)
5. }
6.
7. # Calling the function without giving any argument.
8. new.function()
9.
10. # Calling the function with giving new values of the argument.
11. new.function(4,6)

Output:
R PROGRAMMING

R Built-in Functions
The functions which are already created or defined in the programming framework are known as
a built-in function. R has a rich set of functions that can be used to perform almost every task for
the user. These built-in functions are divided into the following categories based on their
functionality.

Math Functions
R provides the various mathematical functions to perform the mathematical calculation. These
mathematical functions are very helpful to find absolute value, square value and much more
calculations. In R, there are the following functions which are used:
R PROGRAMMING

S. No Function Description Example

1. abs(x) It returns the absolute value of input x. x<- -4


print(abs(x))
Output
[1] 4

2. sqrt(x) It returns the square root of input x. x<- 4


print(sqrt(x))
Output
[1] 2

3. ceiling(x) It returns the smallest integer which is larger than or x<- 4.5
equal to x. print(ceiling(x))
Output
[1] 5

4. floor(x) It returns the largest integer, which is smaller than or x<- 2.5
equal to x. print(floor(x))
Output
[1] 2

5. trunc(x) It returns the truncate value of input x. x<- c(1.2,2.5,8.1)


print(trunc(x))
Output
[1] 1 2 8

6. round(x, digits=n) It returns round value of input x. x<- -4


print(abs(x))
Output
4

7. cos(x), sin(x), tan(x) It returns cos(x), sin(x) value of input x. x<- 4


print(cos(x))
print(sin(x))
print(tan(x))
Output
[1] -06536436
[2] -0.7568025
[3] 1.157821

8. log(x) It returns natural logarithm of input x. x<- 4


print(log(x))
Output
[1] 1.386294
R PROGRAMMING

9. log10(x) It returns common logarithm of input x. x<- 4


print(log10(x))
Output
[1] 0.60206

10. exp(x) It returns exponent. x<- 4


print(exp(x))
Output
[1] 54.59815

String Function
R provides various string functions to perform tasks. These string functions allow us to extract sub
string from string, search pattern etc. There are the following string functions in R:

S. Function Description Example


No

1. substr(x, It is used to extract substrings in a a <- "987654321"


start=n1,stop=n2) character vector. substr(a, 3, 3)
Output
[1] "3"

2. grep(pattern, x , It searches for pattern in x. st1 <- c('abcd','bdcd','abcdabcd')


ignore.case=FALSE, pattern<- '^abc'
print(grep(pattern, st1))
fixed=FALSE)
Output
[1] 1 3

3. sub(pattern, It finds pattern in x and replaces it with st1<- "England is beautiful but no
replacement, x, replacement (new) text. the part of EU"
sub("England', "UK", st1)
ignore.case =FALSE,
Output
fixed=FALSE)
[1] "UK is beautiful but not a part
of EU"

4. paste(..., sep="") It concatenates strings after using sep paste('one',2,'three',4,'five')


string to separate them. Output
[1] one 2 three 4 five

5. strsplit(x, split) It splits the elements of character vector a<-"Split all the character"
x at split point. print(strsplit(a, ""))
R PROGRAMMING

Output
[[1]]
[1] "split" "all" "the"
"character"

6. tolower(x) It is used to convert the string into lower st1<- "shuBHAm"


case. print(tolower(st1))
Output
[1] shubham

7. toupper(x) It is used to convert the string into upper st1<- "shuBHAm"


case. print(toupper(st1))
Output
[1] SHUBHAM

Statistical Probability Functions


R provides various statistical probability functions to perform statistical task. These statistical
functions are very helpful to find normal density, normal quantile and many more calculation. In
R, there are following functions which are used:

Backward Skip 10sPlay VideoForward Skip 10s

S. Function Description Example


No

1. dnorm(x, m=0, sd=1, It is used to find the height of the a <- seq(-7, 7, by=0.1)
log=False) probability distribution at each point to b <- dnorm(a, mean=2.5, sd=0.5)
png(file="dnorm.png")
a given mean and standard deviation
plot(x,y)
dev.off()

2. pnorm(q, m=0, sd=1, it is used to find the probability of a a <- seq(-7, 7, by=0.2)
lower.tail=TRUE, normally distributed random numbers b <- dnorm(a, mean=2.5, sd=2)
png(file="pnorm.png")
log.p=FALSE) which are less than the value of a given
plot(x,y)
number. dev.off()

3. qnorm(p, m=0, sd=1) It is used to find a number whose a <- seq(1, 2, by=002)
cumulative value matches with the b <- qnorm(a, mean=2.5, sd=0.5)
png(file="qnorm.png")
probability value.
plot(x,y)
R PROGRAMMING

dev.off()

4. rnorm(n, m=0, sd=1) It is used to generate random numbers y <- rnorm(40)


whose distribution is normal. png(file="rnorm.png")
hist(y, main="Normal Distribution")
dev.off()

5. dbinom(x, size, prob) It is used to find the probability density a<-seq(0, 40, by=1)
distribution at each point. b<- dbinom(a, 40, 0.5)
png(file="pnorm.png")
plot(x,y)
dev.off()

6. pbinom(q, size, prob) It is used to find the cumulative a <- pbinom(25, 40,0.5)
probability (a single value representing print(a)
the probability) of an event. Output
[1] 0.9596548

7. qbinom(p, size, prob) It is used to find a number whose a <- qbinom(0.25, 40,01/2)
cumulative value matches the print(a)
probability value. Output
[1] 18

8. rbinom(n, size, prob) It is used to generate required number a <- rbinom(6, 140,0.4)
of random values of a given probability print(a)
from a given sample. Output
[1] 55 61 46 56 58 49

9. dpois(x, lamba) it is the probability of x successes in a dpois(a=2, lambda=3)+dpois(a=3,


period when the expected number of lambda=3)+dpois(z=4, labda=4)
events is lambda (λ) Output
[1] 0.616115

10. ppois(q, lamba) It is a cumulative probability of less ppois(q=4, lambda=3,


than or equal to q successes. lower.tail=TRUE)-ppois(q=1,
lambda=3, lower.tail=TRUE)
Output
[1] 0.6434504

11. rpois(n, lamba) It is used to generate random numbers rpois(10, 10)


from the poisson distribution. [1] 6 10 11 3 10 7 7 8 14 12
R PROGRAMMING

12. dunif(x, min=0, This function provide information dunif(x, min=0, max=1, log=FALSE)
max=1) about the uniform distribution on the
interval from min to max. It gives the
density.

13. punif(q, min=0, It gives the distributed function punif(q, min=0, max=1,
max=1) lower.tail=TRUE, log.p=FALSE)

14. qunif(p, min=0, It gives the quantile function. qunif(p, min=0, max=1,
max=1) lower.tail=TRUE, log.p=FALSE)

15. runif(x, min=0, max=1) It generates random deviates. runif(x, min=0, max=1)

Other Statistical Function


Apart from the functions mentioned above, there are some other useful functions which helps for
statistical purpose. There are the following functions:

S. Function Description Example


No

1. mean(x, trim=0, It is used to find the mean for x object a<-c(0:10, 40)
na.rm=FALSE) xm<-mean(a)
print(xm)
Output
[1] 7.916667

2. sd(x) It returns standard deviation of an object. a<-c(0:10, 40)


xm<-sd(a)
print(xm)
Output
[1] 10.58694

3. median(x) It returns median. a<-c(0:10, 40)


xm<-meadian(a)
print(xm)
Output
[1] 5.5
R PROGRAMMING

4. quantilie(x, probs) It returns quantile where x is the numeric vector


whose quantiles are desired and probs is a numeric
vector with probabilities in [0, 1]

5. range(x) It returns range. a<-c(0:10, 40)


xm<-range(a)
print(xm)
Output
[1] 0 40

6. sum(x) It returns sum. a<-c(0:10, 40)


xm<-sum(a)
print(xm)
Output
[1] 95

7. diff(x, lag=1) It returns differences with lag indicating which lag a<-c(0:10, 40)
to use. xm<-diff(a)
print(xm)
Output
[1] 1 1 1 1 1 1 1 1 1
1 30

8. min(x) It returns minimum value. a<-c(0:10, 40)


xm<-min(a)
print(xm)
Output
[1] 0

9. max(x) It returns maximum value a<-c(0:10, 40)


xm<-max(a)
print(xm)
Output
[1] 40

10. scale(x, center=TRUE, Column center or standardize a matrix. a <- matrix(1:9,3,3)


scale=TRUE) scale(x)
Output
[,1]
[1,] -0.747776547
[2,] -0.653320562
[3,] -0.558864577
[4,] -0.464408592
[5,] -0.369952608
[6,] -0.275496623
[7,] -0.181040638
[8,] -0.086584653
R PROGRAMMING

[9,] 0.007871332
[10,] 0.102327317
[11,] 0.196783302
[12,] 3.030462849
attr(,"scaled:center")
[1] 7.916667
attr(,"scaled:scale")
[1] 10.58694

Reading and Writing Data to and from R


Functions for Reading Data into R:
There are a few very useful functions for reading data into R.

1. read.table() and read.csv() are two popular functions used for reading tabular data into
R.
2. readLines() is used for reading lines from a text file.
3. source() is a very useful function for reading in R code files from a another R program.
4. dget() function is also used for reading in R code files.
5. load() function is used for reading in saved workspaces
6. unserialize() function is used for reading single R objects in binary format.

Reading Text Files:

1. Read Lines: To read the content of a text file line by line using the readLines() function.
2. Read Whole Text: To read the entire content of text file into a character vector, use the
readLines() function and then paste().
lines<-readLines(“sample.txt”)
text<-paste(lines,collapse=”\n”)

3. Reading CSV Files: To read from CSV(Comma-Separated Values) file, use the read.csv()
function.
data<-read.csv(“sample.csv”)
print(data)
Id Name Department Salary
1 1 Pradeep IT 35000
2 2 Gayathri Tech 30000
3 3 Rudra Marketing 45000
4 4 Arjun Marketing 55000
5 5 Bheem Tech 50000
6 6 Shakti HR 60000
7 7 Suresh Finance 63000
8 8 Veeresh IT 57000
9 9 Naveen HR 52000
R PROGRAMMING

10 10 Basavaraj Finance 48000

Reading Excel Files:

To read data from an Excel file, use the readxl package’s read_excel() function. First,
install and load the package.

#Install the readxl package if not already installed


#install.packages(“readxl”)
Library(readxl)
d<-read_excel(“data.xlsx”)
# A tibble: 10 × 4
Id Name Department Salary
<dbl> <chr> <chr> <dbl>
1 1 Pradeep IT 35000
2 2 Gayathri Tech 30000
3 3 Rudra Marketing 45000
4 4 Arjun Marketing 55000
5 5 Bheem Tech 50000
6 6 Shakti HR 60000
7 7 Suresh Finance 63000
8 8 Veeresh IT 57000
9 9 Naveen HR 52000
10 10 Basavaraj Finance 48000

Functions for Writing Data to Files:


There are similar functions for writing data to files

1. write.table() is used for writing tabular data to text files (i.e. CSV).
2. writeLines() function is useful for writing character data line-by-line to a file or
connection.
3. dump() is a function for dumping a textual representation of multiple R objects.
4. dput() function is used for outputting a textual representation of an R object.
5. save() is useful for saving an arbitrary number of R objects in binary format to a file.
6. serialize() is used for converting an R object into a binary format for outputting to a
connection (or
file).

Reading Data Files with read.table():


The read.table() function is one of the most commonly used functions for reading data in R. TO
get the help file for read.table() just type ?read.table in R console.

The read.table() function has a few important arguments:


R PROGRAMMING

 file, the name of a file, or a connection


 header, logical indicating if the file has a header line
 sep, a string indicating how the columns are separated
 colClasses, a character vector indicating the class of each column in the dataset
 nrows, the number of rows in the dataset. By default read.table() reads an entire file.
 comment.char, a character string indicating the comment character. This defalts to “#”. If
there are no commented lines in your file, it’s worth setting this to be the empty string “”.
 skip, the number of lines to skip from the beginning
 stringsAsFactors, should character variables be coded as factors? This defaults to TRUE
because back in the old days, if you had data that were stored as strings, it was because
those strings represented levels of a categorical variable. Now we have lots of data that is
text data and they don’t always represent categorical variables. So you may want to set this
to be FALSE in those cases. If you always want this to be FALSE, you can set a global
option via options(stringsAsFactors = FALSE). I’ve never seen so much heat generated on
discussion forums about an R function argument than the stringsAsFactors argument.

readLines() and writeLines() function in R:


readLines() function is mainly used for reading lines from a text file and writeLines() function
is useful for writing character data line-by-line to a file or connection.

Creating a CSV File


A text file in which a comma separates the value in a column is known as a CSV file. Let's
start by creating a CSV file with the help of the data, which is mentioned below by saving
with .csv extension using the save As All files(*.*) option in the notepad.

Example: record.csv

1. id,name,salary,start_date,dept
2. 1,Shubham,613.3,2012-01-01,IT
3. 2,Arpita,525.2,2013-09-23,Operations
4. 3,Vaishali,63,2014-11-15,IT
5. 4,Nishka,749,2014-05-11,HR
6. 5,Gunjan,863.25,2015-03-27,Finance
7. 6,Sumit,588,2013-05-21,IT
8. 7,Anisha,932.8,2013-07-30,Operations
9. 8,Akash,712.5,2014-06-17,Financ

Output
R PROGRAMMING

Reading a CSV file


R has a rich set of functions. R provides read.csv() function, which allows us to read a CSV
file available in our current working directory. This function takes the file name as an input
and returns all the records present on it.

Let's use our record.csv file to read records from it using read.csv() function.

Example

1. data <- read.csv("record.csv")


2. print(data)

When we execute above code, it will give the following output

Output
R PROGRAMMING

Analyzing the CSV File


When we read data from the .csv file using read.csv() function, by default, it gives the
output as a data frame. Before analyzing data, let's start checking the form of our output
with the help of is.data.frame() function. After that, we will check the number of rows
and number of columns with the help of nrow() and ncol() function.

Example

1. csv_data<- read.csv("record.csv")
2. print(is.data.frame(csv_data))
3. print(ncol(csv_data))
4. print(nrow(csv_data))

When we run above code, it will generate the following output:

Output
R PROGRAMMING

Writing Data to text files:

d<-c(1,2,3,4,5)
write(d,”output.txt”)
Example using cat()
d<-c(1,2,3,4,5)
cat(d, file=”sample.txt”, sep=”\n”)

Writing data to CSV Files


To write data to a CSV file, you can use the write.csv() function.

Ex:
d<-data.frame(Name=c(“Alice”,”Bob”,”Charlie”), Age=c(25, 30, 28))
write.csv(d,”output.csv”,row.names=FALSE)

Writing data to Excel Files


To write data to excel file, you can use the writexl package’s write_xlsx() function. First, make
sure to install and load the package.

Ex:
#install the writexl package if not already installed
#install.packages(“writexl”)
library(writexl)
d<-data.frame(Name=c(“Alice”,”Bob”,”Charlie”), Age=c(25, 30, 28))
write_xlsx(d, “output.xlsx”)

Writing Data to other Data Formats:


R supports writing data to various other formats like JSON, XML and SQL databases using
specific packages and functions.

File and Directory Functions


1. read.csv()
the read.csv() function in R is used to read data from CSV file and store it in a data
frame. CSV files are a common way to store structured data where values are separated
by commas or other delimiters.
2. Str()
The str() function in R is used to display the structure of an R object. It provides a
concise and informative summary of the internal structure of an R object, including its
data type, the number of elements or components and the names of the elements.

str(read.csv("Sample.csv"))

'data.frame': 10 obs. of 4 variables:


$ Id : int 1 2 3 4 5 6 7 8 9 10
$ Name : chr "Pradeep" "Gayathri" "Rudra" "Arjun" ...
R PROGRAMMING

$ Department: chr "IT" "Tech" "Marketing" "Marketing" ...


$ Salary : int 35000 30000 45000 55000 50000 60000 63000 57000 52000 48000

3. head()
the head() function in R is used to display the first few rows of data frame, matrix, or
other tabular data structure. It’s a handy tool for quickly inspecting the structure and
contents of a dataset without displaying the entire dataset.

head(d,n=6)
d: the data frame, matrix, or other data structure you want to display
n: the number of rows you want to display (default is 6)

> head(d,n=6)

Id Name Department Salary


1 1 Pradeep IT 35000
2 2 Gayathri Tech 30000
3 3 Rudra Marketing 45000
4 4 Arjun Marketing 55000
5 5 Bheem Tech 50000
6 6 Shakti HR 60000

4. tail()
the tail() function in R is used to display the last few rows of a data frame, matrix, or
other tabular data structure. It’s the counterpart to the head() function.

> tail(d,n=6)
Id Name Department Salary
5 5 Bheem Tech 50000
6 6 Shakti HR 60000
7 7 Suresh Finance 63000
8 8 Veeresh IT 57000
9 9 Naveen HR 52000
10 10 Basavaraj Finance 48000

5. nrow & ncol:


the nrow() and ncol() functions are used to determine the number of rows and columns
respectively, in a data frame, matrix or other tabular data structure.

nrow() returns the number of rows in the specified data structure.


ncol() returns the number of columns in the specified data structure.
R PROGRAMMING

6. table()
The table() function in R is used to create frequency tables , which are particularly
useful for summarizing categorical data by counting the number of occurrences of each
category.
table(“”)

table(d$Department)

Finance HR IT Marketing Tech


2 2 2 2 2

7. rbind():
rbind() is a function to combine two or more f=data frame, matrices or vectors by row.
It is short for “row bind” and is commonly used when you want to stack or append data
vertically.

rbind(object1, object2, …)

create two sample data frames


df1<-data.frame(Name=c(“Alice”, “Bob”, “Charlie”), Age=c(25, 30, 28))
df2<-data.frame(Name=c(“David”,”Eve”), Age=c(26, 28))
com_df<-rbind(df1,df2)
> print(com_df)
Name Age
1 Alice 25
2 Bob 30
3 Charlie 28
4 David 26
5 Eve 28
R PROGRAMMING

Exceptions:

The exception-handling facilities in R are provided through two mechanism. Functions


such as stop or warning can be called directly or option such as “warn” can be used to control
the handling of problems.

Exceptions can be handled using the tryCatch function. Exceptions or errors occur
when something unexpected happens during the execution of your code, such as attempting to
access a nonexistent variable or divide by zero. Here’s how you can use tryCatch to handle
exceptions in R.

Syntax:

res<-tryCatch(
expression,
error=function(err){
#code to handle errors
},
warning =function(warn){
#code to handle warnings
},
message=function(msg){
#code to handle messages
}
)

Ex: Function that may throw an error

div_num<-function(a,b)
if(b==0){
stop(“Division by zero is not allowed”)
}
return(a/b)
}
# Using tryCatch to handle the exception
Res<-tryCatch(
div_num(10,0),
error=function(err){
cat(“An error occurred:”,conditionMessage(err),”\n”)
return(NA) #return default value
}
)
cat(“Result: ”,res,”\n”)
R PROGRAMMING

Output: An error occurred: Division by zero is not allowed,


Result: NA

Stop():
Stop() function is used to generate an error message and stop the execution of the program or
function when a certain condition is met. It allows to explicit termination of the program with
an error message of choice. A call to stop halts the evaluation of the current expression, prints
the message argument, and returns execution to the top level.

The basic syntax of the stop() function is as follows:


stop(“Error Message”)

Ex:
x<-5
if(x<0){
stop(“Value of ‘x’ should be non-negative.”)
}
cat(“This line will not be executed because of the stop() function”)

output:
Error: Value of ‘x’ should be non-negative.
Execution halted.

If the value of x is negative, the stop() function is called, and the program is terminated
with the error message “Value of ‘x’ should be non-negative.” The code that follows the dtop()
statement will not be executed.

Warning():
Warnings are used to alert the user or developer about potential issues or non-fatal
problems that might have occurred during the execution of a function or code.

Syntax:
Warning(“Warning message”)

Ex:
x<- -5
if(x<0){
warning(“Value of ‘x’ is negative. This may cause unexpected results”)
}
cat(“This line will still be executed despite the warning.”)

Output:
Warning message:
Value of ‘x’ is negative. This may cause unexpected results.
R PROGRAMMING

Warn:
The warn option allows to specify the behavior of warnings. There are several levels of warn
option:
warn=0: Warnings are turned off. This means that warnings will not be displayed, and the
program will continue without interruption.
warn=1: The default settings. Warnings are displayed as they occur.
warn=2: Warnings are turned into errors. When a warning occurs, it is treated as an error, and
the program terminates.

Set the Warn option


Options(warn=1) # set the warning level to 1(default)

Ex: to suppress warnings and to display them, set the warn option to 0.

Options(warn=0) # turn off warnings


To treat warnings as errors and stop the program when a warning is issued , set the warn option
to 2:

Options(warn=2) # Treat warnings as errors

Changing the warn can be useful when we want to customize how warnings are handled within
your R code. However, it is essential to use these options carefully, as turning off warnings
(setting warn to 0) may hide important information about potential issues in your code.
Treating warnings as errors (setting warn to 2) can help catch problems early but might be
overly strict in some cases.

Ex:
#Function that generates a warning for even numbers
geteven<-function(x)
if (x%%2==0){
warning(“Even number detected. This function works best with odd numbers”)
}
return(x*2)
}
geteven(5)

Output:
[1] 10

A program to read a file that may or may not exist and we’ll gracefully handle the exception
if the file doesn’t exist:
rf<-function(file_path){
tryCatch(
{
data<-read.csv(file_path) #Try to read the file
R PROGRAMMING

return(data)
},
error=function(err){
cat(“Error occurred while reading the file:”,conditionMessage(err),”\n”)
return(NULL)
}
)
}
#Test the function with a file that may or may not exist
file_path<-“non_existant_file.csv”
result<-read_file(file_path)
if(is.null(result)){
cat(“File not found or an error occurred. Please check the file path. \n”
}else{
cat(“File read successfully, \n”)
}

Output:
Warning message:
In file(file,”rt”)
Cannot open file ‘non_existent_file.csv’: No such file or directory.

Visibility:
Visibility refers to the accessibility of objects (variables, functions, classes etc) from one part
of your code to another. It relates to how objects are scoped and whether they can be used and
manipulated in different part of your R script or program. R uses various mechanisms for
managing the visibility of objects, including lexical scoping, environment and packages.

Lexical scoping:
R uses lexical scoping, which means that objects are typically visible in the
environment or scope in which they are defined. Functions, for ex. Have access to variables in
the same environment in which they were created.

Ex:
x<-5 # x is defined in the global environment
my_fun<-function(){
y<-10 #y is defined as the local environment
res<-x+y
return(res)
}
my_fun()

Output:
[1] 15
R PROGRAMMING

Environments:
R allows to create and manage environments, which are like separate containers for objects to
control the visibility of objects by placing them in specific environments.

Ex:
env<-new.env() #Create a new environment
env$x<-5 #Define x in from the environment
my_fun<-function(){
res<-env$x # Access x from the environment
return(res)
}
my_fun()

Output:
[1] 5

Check availability R Packages


Get library locations containing R packages
Ex: .libPaths()
When we execute the above code, it produces the following result

Output:
> .libPaths()
[1] "C:/Users/MANJESH/AppData/Local/R/win-library/4.3"
[2] "C:/Program Files/R/R-4.3.1/library"

Get the list of all the Packages Installed


Library()
R PROGRAMMING

Get all packages currently loaded in the R environment


Search()
When we execute the above code, it produces the following result. It may vary depending on
the local settings of your pc.

> library()
> search()
[1] ".GlobalEnv" "package:stats" "package:graphics"
[4] "package:grDevices" "package:utils" "package:datasets"
[7] "package:methods" "Autoloads" "package:base"

Install the new packages:


There are two ways to add new R packages. One is installing directly from CRAN directory
and another is downloading the package to your local system and installing it manually.

Install Directly from CRAN:


The following command gets the packages directly from CRAN webpage and installs the
package in the R environment. You may be prompted to choose the nearest mirror. Choose the
one appropriate to your location.

Install.packages(“Package Name”)

#install the packages named “XML”


Install.packages(“XML”)

Install package manually:


Go to the link R packages to download the package needed. Save the package as a .zip file in
a suitable location in the local system use the following command to install this package in the
R environment.

install.packages(file_name_with_path, repos=NULL, type=”source”)


#install the package names “XML”
install.packages(“E:/XML_3.98-1.3.zip”,repos=NULL, type=”source”)

Load package to Library


Before a package can be used in the code, it must be loaded to the current R environment. You
also need to load a package that is already installed previously but not available in the current
environment. A package is loaded using the following command-
Library(“package name”,lib.loc=”path to library”)

You might also like