0% found this document useful (0 votes)
59 views44 pages

Introduction To R: Session 6

This document discusses different types of loops in R including while loops, for loops, and repeat loops. It provides examples of how to use each loop type, explaining the syntax and how varying elements like conditions, increments, and breaks control the loop execution. Key loop concepts covered are how while and repeat loops repeat until a condition is met, while for loops iterate over a set of values.

Uploaded by

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

Introduction To R: Session 6

This document discusses different types of loops in R including while loops, for loops, and repeat loops. It provides examples of how to use each loop type, explaining the syntax and how varying elements like conditions, increments, and breaks control the loop execution. Key loop concepts covered are how while and repeat loops repeat until a condition is met, while for loops iterate over a set of values.

Uploaded by

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

INTRODUCTION TO R Session 6

1
WHILE LOOP
2
R-WHILE LOOP
The While loop executes the same code again and again until a
stop condition is met. the condition part of this recipe should
become FALSE at some point during the execution. Otherwise,
the while loop will go on indefinitely.
Syntax
The basic syntax for creating a while loop in R is −

Here key point of the while loop is that the loop might


while (test_expression) {
not ever run. When the condition is tested and the result
statement is false, the loop body will be skipped and the first
statement after the while loop will be executed.
}
3
EXAMPLE
Code Output
v <- c("Hello","while loop") [1] "Hello" "while loop"
cnt <- 2 [1] "Hello" "while loop"
[1] "Hello" "while loop"
while (cnt < 7) { [1] "Hello" "while loop"
print(v) [1] "Hello" "while loop"
cnt = cnt + 1
}
4
TO PRINT NOS. I-9
[1] 1 i is initially initialized to 1.
i <- 1
[1] 2 Here, the test_expression is i < 10 which evaluates to TRUE
while (i < 10) { since 1 is less than 10. So, the body of the loop is entered
[1] 3
print(i) and i is printed and incremented.
[1] 4
i = i+1 Incrementing i is important as this will eventually meet the
[1] 5 exit condition. Failing to do so will result into an infinite
} loop.
[1] 6
[1] 7 In the next iteration, the value of i is 2 and the loop
continues.
[1] 8
[1] 9 This will continue until i takes the value 10. The condition
10 < 10 will give FALSE and the while loop finally exits.
5
CHECKING THE SPEED USING
A WHILE LOOP
# Initialize the speed variable
speed <- 64
# Code the while loop
while (speed>30 ) {
print("Slow down!")
speed <- speed-7
}
# Print out the speed variable
speed
6
# Initialize the speed variable

WHILE-IF-ELSE speed <- 64


# Extend/adapt the while loop
while (speed > 30) {
Initialize the speed to 64
print(paste("Your speed is", speed))
Use the while loop to set a condition
if (speed > 48) {
Check if Speed > 30 in the while loop
print("Slow down big time!")
If the speed is greater than 48, have R
print out "Slow down big time!", and speed <- speed - 11 } else {
decrease the speed by 11. print("Slow down!")
Otherwise, have R simply print out speed <- speed - 6 }
"Slow down!", and decrease the speed
by 6. }

7
# Initialize the speed variable
speed <- 88

BREAK CONDITION while (speed > 30) {


print(paste("Your speed is", speed))
# Break the while loop when speed exceeds
80
The break statement is a control
statement. When R encounters it, the if (speed>80 ) {
while loop is abandoned completely break() }
if (speed > 48) {
print("Slow down big time!")
speed <- speed - 11 } else {
print("Slow down!")
speed <- speed - 6
}
}

8
FOR LOOP
This for loop consists of the following parts:
for(i in values){
✓ The keyword for, followed by parentheses.
. . . do something . . .
✓ An identifier between the parentheses. In this example, we use i, but
}
that can be any object name you like.
✓ The keyword in, which follows the identifier.
✓ A vector with values to loop over. In this example code, we use the
object values, but that again can be any vector you have available.
✓ A code block between braces that has to be carried out for every value
in the object values

9
TO PRINT VALUES FROM 1-10
for(i in 1:10) [1] "Values of i= 1"

{ [1] "Values of i= 2"


[1] "Values of i= 3"
print (paste("Values of i=",i))
[1] "Values of i= 4"
}
[1] "Values of i= 5"
[1] "Values of i= 6"
[1] "Values of i= 7"
[1] "Values of i= 8"
[1] "Values of i= 9"
[1] "Values of i= 10"
10
REPEAT LOOP
The repeat loop is similar to the while condition except that it has no
condition. The repeat loop continuously checks single or multiple statements
and goes into an infinite loop. Hence, the user needs to use the break
statement to terminate the continued execution of a loop. If it is not used then
the loop becomes infinite and executes the statement infinite no. of times

11
print("Repeat Statement")

REPEAT i<-1
repeat
{
Loop variable initialization
print(paste("i=",i))
repeat
i=i+1
{
if(i==10)
statements
{
Loop variable increment/decrement
break ()
Break statement
}
}
}
print("the repeat loop breaks the loop
after 10")
12
GRAPHICS
13
STARTING OUT WITH GRAPHS
# Creating a Graph
attach(mtcars)
plot(wt, mpg)
abline(lm(mpg~wt))
title("Regression of MPG on Weight")

The plot( ) function opens a graph window


and plots weight vs. miles per gallon.
The next line of code adds a regression line
to this graph. The final line adds a title. mpg~cyl: This formula reads as “plot boxes for
the variable mpg for the groups defined by the
In R, the lm(), or “linear variable cyl.” Refer Pg. 288 in Dummies .
model,” function can be used to create a It also means miles per gallon explained by
simple regression model weight 
14
CREATING A BAR PLOT
Bar plots can be created in R using the barplot() function. We can supply a vector or
matrix to this function. If we supply a vector, the plot will have bars with their
heights equal to the elements in the vector.
height <- c(122, 128, 136, 124, 133, 156, 128)
barplot(height)
Some of the frequently used arguments are, main to give the title, xlab and ylab to
provide labels for the axes, names.arg for naming each bar, col to define color etc.
We can also plot bars horizontally by providing the argument horiz = TRUE.

15
BAR PLOTS

H <- c(7,12,28,3,41)
M <- c("Mar","Apr","May","Jun","Jul")

barplot(H, names.arg=M, xlab="Month", ylab="Revenue",col="blue", main="Revenue


chart",border="red")

16
EXERCISE:
1. Write a R program to create a simple bar plot of five subjects marks.

marks = c(70, 95, 80, 74)


barplot(marks,
main = "Comparing marks of 5 subjects",
xlab = "Marks",
ylab = "Subject",
names.arg = c("English", "Science", "Math.", "Hist."),
col = "darkred",
horiz = FALSE)
17
STACKED BAR GRAPH
colors = c("green","orange","brown")
months <- c("Mar","Apr","May","Jun","Jul")
regions <- c("East","West","North")

# Create the matrix of the values.


Values <- matrix(c(2,9,3,11,9,4,8,7,3,12,5,2,8,10,11),
nrow = 3, ncol = 5, byrow = TRUE)
barplot(Values, main = "total revenue", names.arg = Cex - number indicating the amount by which
months, xlab = "month", ylab = "revenue", col = colors) plotting text and symbols should be scaled relative
to the default. 1=default, 1.5 is 50% larger, 0.5 is
legend("topleft", regions, cex = 1.3, fill = colors) 50% smaller, etc.
18
BOX PLOT
Boxplots are a measure of how well distributed is the data in a data set. It divides the data set into three quartiles. This
graph represents the minimum, maximum, median, first quartile and third quartile in the data set. It is also useful in
comparing the distribution of data across data sets by drawing boxplots for each of them.
Boxplots are created in R by using the boxplot() function.
boxplot(x, data, notch, varwidth, names, main)
Following is the description of the parameters used −
x is a vector or a formula.
data is the data frame.
notch is a logical value. Set as TRUE to draw a notch.
varwidth is a logical value. Set as true to draw width of the box proportionate to the sample size.
names are the group labels which will be printed under each boxplot.
main is used to give a title to the graph
19
BOX-PLOT

mpg~cyl: This formula reads as “plot boxes for


print(mtcars) the variable mpg for the groups defined by the
variable cyl.” Refer Pg. 288 in Dummies .
input <- mtcars[,c('mpg','cyl')] It also means miles per gallon explained by
weight 
print(head(input))
boxplot(mpg ~ cyl, data = mtcars, xlab = "Number of Cylinders",
ylab = "Miles Per Gallon", main = "Mileage Data")
20
NOTCHED
# Plot the chart.
boxplot(mpg ~ cyl, data = mtcars,
xlab = "Number of Cylinders",
ylab = "Miles Per Gallon",
main = "Mileage Data",
varwidth is a logical value. Set as true to draw
notch = TRUE, width of the box proportionate to the sample size.
names are the group labels which will be printed
varwidth = TRUE,
under each boxplot. main is used to give a title to
col = c("green","yellow","purple"), the graph.
names = c("High","Medium","Low")
)
21
HISTOGRAMS AND DENSITY
PLOTS
Histograms
A histogram represents the frequencies of values of a variable bucketed into ranges.
Histogram is similar to bar chat but the difference is it groups the values into
continuous ranges. Each bar in histogram represents the height of the number of
values present in that range.
R creates histogram using hist() function. This function takes a vector as an input
and uses some more parameters to plot histograms. The function hist(x) where x is a
numeric vector of values to be plotted. The option freq=FALSE plots probability
densities instead of frequencies. The option breaks= controls the number of bins.

22
The basic syntax for creating a histogram using R is −
hist(v,main,xlab,xlim,ylim,breaks,col,border)
Following is the description of the parameters used −

 v is a vector containing numeric values used in histogram.


 main indicates title of the chart.
 col is used to set color of the bars.
 border is used to set border color of each bar.
 xlab is used to give description of x-axis.
 xlim is used to specify the range of values on the x-axis.
 ylim is used to specify the range of values on the y-axis.
 breaks is used to mention the width of each bar
23
HISTOGRAM

# Create data for the graph.


v <- c(9,13,21,8,36,28,12,41,31,33,19)
# Create the histogram.
hist(v,xlab = "Weight",col = "red",border = "yellow")
To specify the range of values allowed in X axis and Y axis, we can use the xlim and ylim
parameters.
hist(v,xlab = "Weight",col = "green",border = "red", xlim = c(0,40), ylim = c(0,5),
breaks = 5)
24
LINE CHART
A line chart is a graph that connects a series of points by drawing line segments
between them. These points are ordered in one of their coordinate (usually the x-
coordinate) value. Line charts are usually used in identifying the trends in data.
The plot() function in R is used to create the line graph.
Syntax
The basic syntax to create a line chart in R is −
plot(v,type,col,xlab,ylab)

25
LINE CHART
plot(v,type,col,xlab,ylab)
Following is the description of the parameters used −
v is a vector containing the numeric values.
type takes the value "p" to draw only the points, "l" to draw only the lines and "o" to
draw both points and lines.
xlab is the label for x axis.
ylab is the label for y axis.
main is the Title of the chart.
col is used to give colors to both the points and lines
26
LINE PLOT
# Create the data for the chart.
v <- c(7,12,28,3,41)
# Plot the bar chart.
plot(v,type = "o")

27
LINE PLOT

Line Chart Title, Color and Labels


The features of the line chart can be expanded by using additional parameters. We add color to the
points and lines, give a title to the chart and add labels to the axes.
# Create the data for the chart.
v <- c(7,12,28,3,41)
# Plot the bar chart.
plot(v, type = "o", col = "red", xlab = "Month", ylab = "Rain fall", main = "Rain fall
chart")
28
MULTIPLE LINES

v <- c(7,12,28,3,41)
t <- c(14,7,6,19,3)
# Plot the bar chart.
plot(v,type = "o",col = "red", xlab = "Month", ylab = "Rain fall", main = "Rain fall chart")
lines(t, type = "o", col = "blue")

29
SCATTER PLOTS
Scatterplots show many points plotted in the Cartesian plane. Each point represents the
values of two variables. One variable is chosen in the horizontal axis and another in the
vertical axis.
The basic syntax for creating scatterplot in R is −
plot(x, y, main, xlab, ylab, xlim, ylim, axes)
Following is the description of the parameters used −
x is the data set whose values are the horizontal coordinates.
y is the data set whose values are the vertical coordinates.
main is the tile of the graph.
xlab is the label in the horizontal axis.
ylab is the label in the vertical axis.
xlim is the limits of the values of x used for plotting.
ylim is the limits of the values of y used for plotting.
axes indicates whether both axes should be drawn on the plot

30
SCATTER PLOT

plot (wt, mpg, main="Scatterplot Example", xlab="Car Weight ",


ylab="Miles Per Gallon ", pch=19)

31
PIE CHARTS
Pie chart is drawn using the pie() function in R programming . Pie charts are created
with the function pie(x, labels=) where x is a non-negative numeric vector indicating the
area of each slice and labels= notes a character vector of names for the slices
items<-c("housing", "food", "clothes", "rent", "other")
expenses<-c(600,300,150,100,200)
pie(expenses, labels=items)

32
SIMPLE PIE CHART
# Simple Pie Chart
slices <- c(10, 12,4, 16, 8)
lbls <- c("US", "UK", "Australia", "Germany", "France")
pie(slices, labels = lbls, main="Pie Chart of Countries")

33
PIE CHART WITH
PERCENTAGES
# Pie Chart with Percentages
slices <- c(10, 12, 4, 16, 8)
lbls <- c("US", "UK", "Australia", "Germany", "France")
pct <- round(slices/sum(slices)*100)
lbls <- paste(lbls, pct) # add percents to labels
lbls <- paste(lbls,"%",sep="") # ad % to labels
pie(slices,labels = lbls, col=rainbow(length(lbls)),
main="Pie Chart of Countries")

34
3-D PIE CHART
# 3D Exploded Pie Chart
library(plotrix)
slices <- c(10, 12, 4, 16, 8)
lbls <- c("US", "UK", "Australia", "Germany",
"France")
pie3D(slices,labels=lbls,explode=0.1,
main="Pie Chart of Countries ")

35
R LAB Practice

36
EXERCISE 1
Write a R program to take input from the user (name and gender) and display the
values. Also print the version of R installation.

Source causes R to accept its input from the named file or URL or connection or expressions directly. ... Its main
purpose is to evaluate and auto-print expressions as if in a top level context, e.g, as in the R console.
SOLUTION EXERCISE 1
Write a R program to take input from the user (name and gender) and display the
values. Also print the version of R installation.

name <- readline(prompt="Input your name: ")


gender <- readline(prompt="Input your gender: ")
print(paste("My name is" ,name, "and my gender is" ,gender,"."))
print(R.version.string)

Use ctrl + shift + enter on the console


EXERCISE 2
Write a R program to create a sequence of numbers from 20 to 50 and find the mean of
numbers from 20 to 60 and sum of numbers from 51 to 91.
Use the sequence function seq (10,20) prints the output as
seq(20,30)
[1] 20 21 22 23 24 25 26 27 28 29 30
SOLUTION - EXERCISE 2
Write a R program to create a sequence of numbers from 20 to 50 and find the mean of
numbers from 20 to 60 and sum of numbers from 51 to 91.
Use the sequence function seq (10,20) prints the output as
seq(20,30)
[1] 20 21 22 23 24 25 26 27 28 29 30

print("Sequence of numbers from 30 to 60:")


print(seq(30,60))
print("Mean of numbers from 30 to 60:")
print(mean(30:60))
print("Sum of numbers from 30 to 60:")
print(sum(30:60))
EXERCISE 3
Write a R program to create a vector which contains 10 random integer values between -50
and +50.
SOLUTION - EXERCISE 3
Write a R program to create a vector which contains 10 random integer values between -50
and +50.

v = sample(-50:50, 10, replace=TRUE)


print("Content of the vector:")
print("10 random integer values between -50 and +50:")
print(v)
EXERCISE 4
Write a R program to generate Fibonacci numbers
The Fibonacci sequence, such that each number is the sum of the two preceding ones
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181,
6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811,
n<-readline("Enter limit for series")
n<-as.integer(n)

SOLUTION- EXERCISE 4
fibbo(n)
print("Fibonaci Series")
a<-1
b<-1
fibbo<-function (n)
{
while(n>0)
{
s<-a+b
print(s)
a=b
b=s
n<-n-1

You might also like