0% found this document useful (0 votes)
2 views9 pages

R Programming Loop

The document provides an overview of loops in R programming, including for loops, while loops, and repeat loops, along with examples for each type. It also discusses vectorized code, which allows for faster operations on entire vectors or arrays instead of using explicit loops. Practical questions are included to reinforce the concepts of loops and vectorization.

Uploaded by

adeeshaikh4
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)
2 views9 pages

R Programming Loop

The document provides an overview of loops in R programming, including for loops, while loops, and repeat loops, along with examples for each type. It also discusses vectorized code, which allows for faster operations on entire vectors or arrays instead of using explicit loops. Practical questions are included to reinforce the concepts of loops and vectorization.

Uploaded by

adeeshaikh4
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

R Programming

Merchant Abubakar Yusuf


2.4. LOOPS 31

2.4 Loops
2.4.1 Expected Values (Loop Variable Values)
The expected values in a loop refer to the values that the loop variable will take during
the execution of the loop.

Examples

# Example 1: For loop 1 to 5


for ( i in 1:5) {
print ( i ) # Expected values : 1 ,2 ,3 ,4 ,5
}

# Example 2: Vector loop


vec <- c (10 ,20 ,30)
for ( v in vec ) {
print ( v ) # Expected values : 10 ,20 ,30
}

# Example 3: Sequence with step


for ( j in seq (2 ,10 ,2)) {
print ( j ) # Expected values : 2 ,4 ,6 ,8 ,10
}

# Example 4: Nested loop


for ( a in 1:2) {
for ( b in 1:3) {
cat ( " a = " ,a , " b = " ,b , " \ n " )
# Expected values : (1 ,1) ,(1 ,2) ,(1 ,3) ,(2 ,1) ,(2 ,2) ,(2 ,3)
}
}

2.4.2 Cartesian Product ([Link]())


In the context of loops, [Link]() is used to generate all possible combinations of
loop variables. This is useful when multiple nested loops are needed.

Examples

# Example 1: Two variables


grid <- expand . grid ( x =1:2 , y =3:4)
grid # All combinations of x and y

# Example 2: Three variables


grid <- expand . grid ( A =1:2 , B = c ( " X " ," Y " ) , C = TRUE : FALSE )
grid
32 MODULE 2. R PROGRAMMING TECHNIQUE

2.4.3 For Loops


A for loop repeatedly executes a block of code for each value of a loop variable, which
takes values from a sequence or vector.

Examples
# Example 1: Print 1 to 5
for ( i in 1:5) {
print ( i )
}

# Example 2: Sum numbers 1 to 10


total <- 0
for ( i in 1:10) {
total <- total + i
}
total

# Example 3: Loop through a vector


vec <- c (2 ,4 ,6)
for ( v in vec ) {
print ( v ^2)
}

# Example 4: Nested for loop


for ( i in 1:2) {
for ( j in 1:3) {
cat ( " i = " ,i , " j = " ,j , " \ n " )
}
}

2.4.4 While Loops


A while loop executes a block of code repeatedly as long as a specified condition is
TRUE. The loop variable is updated within the loop.

Examples
# Example 1: Print 1 to 5
i <- 1
while ( i <= 5) {
print ( i )
i <- i + 1
}

# Example 2: Sum until exceeding 20


sum _ val <- 0
i <- 1
2.4. LOOPS 33

while ( sum _ val <= 20) {


sum _ val <- sum _ val + i
i <- i + 1
}
sum _ val

# Example 3: Random number until >0.9


x <- 0
while ( x <= 0.9) {
x <- runif (1)
print ( x )
}

# Example 4: Factorial calculation


n <- 5
fact <- 1
i <- 1
while ( i <= n ) {
fact <- fact * i
i <- i + 1
}
fact

2.4.5 Repeat Loops


A repeat loop executes code repeatedly until a break statement is encountered. It is
useful when the number of iterations is unknown in advance.

Examples
# Example 1: Print 1 to 5
i <- 1
repeat {
print ( i )
i <- i + 1
if ( i > 5) break
}

# Example 2: Sum until exceeding 20


sum _ val <- 0
i <- 1
repeat {
sum _ val <- sum _ val + i
i <- i + 1
if ( sum _ val > 20) break
}
sum _ val

# Example 3: Random number until >0.9


repeat {
34 MODULE 2. R PROGRAMMING TECHNIQUE

x <- runif (1)


print ( x )
if ( x > 0.9) break
}

# Example 4: Factorial calculation


n <- 5
fact <- 1
i <- 1
repeat {
fact <- fact * i
i <- i + 1
if ( i > n ) break
}
fact

2.5 Vectorized Code


Vectorized code in R uses operations on entire vectors or arrays at once instead of iterating
element by element. This is much faster than using explicit loops.

Examples
# Example 1: Adding two vectors
x <- 1:5
y <- 6:10
z <- x + y # Vectorized addition

# Example 2: Squaring each element


v <- 1:5
v ^2 # Vectorized squaring

# Example 3: Logical comparison


a <- c (1 ,3 ,5)
a > 2 # Vectorized comparison

# Example 4: Sum of squares


sum ( v ^2) # Vectorized sum

2.5.1 How to Vectorize?


Vectorization involves replacing explicit loops with R functions that operate on whole
vectors, matrices, or arrays. Common approaches include using arithmetic on vectors,
apply() family, and built-in vectorized functions.

Examples
2.5. VECTORIZED CODE 35

# Example 1: Replace for loop with vectorized addition


x <- 1:5
y <- 6:10
# Loop
z <- numeric ( length ( x ))
for ( i in 1: length ( x )) { z [ i ] <- x [ i ]+ y [ i ] }
# Vectorized
z <- x + y

# Example 2: Vectorized function using sqrt


v <- c (4 ,9 ,16)
sqrt ( v ) # Instead of looping

# Example 3: Using ifelse


x <- 1:5
ifelse ( x %% 2 == 0 , " Even " , " Odd " ) # Vectorized conditional

Practical Questions
Example 1:
Write a for loop to calculate and print the sum of first 10 natural numbers (1+2+...+10).
Store the result in a variable total sum. aslo write the code for Vectorized addition for
the sum of first 10 natural numbers.

Example 2:
Write an R program to print the multiplication table of 5 using a for loop.

Example 3:
Write an R program to find the factorial of a number using a while loop. (find n!, n
from user input)
# Example 1: Sum of first 10 natural numbers

# Using for loop


total _ sum <- 0
for ( i in 1:10) {
total _ sum <- total _ sum + i
}
print ( total _ sum )

# Using vectorized addition


total _ sum _ vec <- sum (1:10)
print ( total _ sum _ vec )

# Example 2: Multiplication table of 5

for ( i in 1:10) {
36 MODULE 2. R PROGRAMMING TECHNIQUE

print ( paste ( " 5 x " , i , " = " , 5 * i ))


}

# Example 3: Factorial using while loop

n <- as . numeric ( readline ( " Enter a number : " ))


fact <- 1
i <- 1

while ( i <= n ) {
fact <- fact * i
i <- i + 1
}

print ( paste ( " Factorial is " , fact ))


2.5. VECTORIZED CODE 37

Practical Questions
Example 1:
Write nested for loops to print a 3×3 grid of asterisks (*) like:

* * *
* * *
* * *

Example 2:
Write R code to print:

1
2 2
3 3 3
4 4 4 4

Example 3:
Write the R program to print:

* * * *
* * *
* *
*

# Example 1: 3 3 grid of asterisks

for ( i in 1:3) {
for ( j in 1:3) {
cat ( " * " )
}
cat ( " \ n " )
}

cat ( " \ n " )

# Example 2: Number pattern

for ( i in 1:4) {
for ( j in 1: i ) {
cat (i , " " )
}
cat ( " \ n " )
}

cat ( " \ n " )


38 MODULE 2. R PROGRAMMING TECHNIQUE

# Example 3: Inverted star pattern

for ( i in 4:1) {
for ( space in 0:(4 - i )) {
cat ( " " )
}
for ( star in 1: i ) {
cat ( " * " )
}
cat ( " \ n " )
}

You might also like