R Program to looping over objects in r programming


March 20, 2022, Learn eTutorial
1103

How to iterate over all the elements of a vector and print the current value

Here we are explaining how to write an R program to iterate over all the elements of a vector and print the current value. Here we are using for loop for the iteration. The syntax of sorting is like

for (val in sequence)
{
statement
} 

Here, the sequence may be a vector and val takes on each of its values during the loop. In each iteration of the loop, the statement is evaluated.

How to iterate over all the elements of a vector and print the current value in the R program

Below are the steps used in the R program to iterate over all the elements of a vector and print the current value. In this R program, we directly give the values iterative for loop. The variable fruit indicating the vector of fruits. iterate through vector fruit using the variable i. In each iteration print i th value.

ALGORITHM

STEP 1: Assign variable fruit with vector values

STEP 2: Call for loop for iterate through vector values

STEP 3: Go through each of the ith values of fruit vector

STEP 4: Print each of the ith value

 

R Source Code

                                          # Create fruit vector
fruit <- c('Banana', 'Orange', 'Mango, 'Apple')
# Create the for statement
for ( i in fruit){ 
 print(i)
}
                                      

OUTPUT

## [1] "Banana"
## [1] "Orange"
## [1] "Mango"
## [1] "Apple"