Looping in R

LOOPS in R

Loops are part of iterative programming where the user wants to perform a sequence of instructions N number of times.

R provides 3 styles of loops:

  1. For Loop
  2. While Loop
  3. Repeat Loop

For Loop

For loops are used when we want to iterate over a sequence like vectors and or data frames.

Syntax:
v<-c(10,21,11,31,88,78)
for(i in v){
      print(i)
}

This will iterate over all the elements of vector v.










For iterating over individual elements using the index one can use sequence vector and use it as index.

Syntax:
v<-c(10,21,11,31,88,78)
for(i in 1:length(v)){
      print(v[i])
}



While Loop

While loops are used when the iterations depend on a condition and it is difficult to predict the number of iterations.

SYNTAX:

i<-2
while(i<=10){
         print(i)
         i<-i+2
}


Repeat

Repeat is a new construct available only in R to run an infinite loop. Repeat block will iterate until a break statement is encountered.

SYNTAX:

i<-2
repeat{
     print(i)
     if(i>10){
            break
     }
}




Comments

Popular posts from this blog

Word Vectorization

Spidering the web with Python

Machine Learning -Solution or Problem