R Program to looping over objects

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)
}
## [1] "Banana"
## [1] "Orange"
## [1] "Mango"
## [1] "Apple"

R Source Code

# Create item vector
item <- c('Paper', 'Pen', 'Pencil', 'Board')

# Create the for statement
for(i in item){ 
               print(i)
            }
## [1] "Paper"
## [1] "Pen"
## [1] "Pencil"
## [1] "Board"