November 9, 2020

R for while repeat Loops

for while repeat loops in R

for loop syntax:
for (variable in sequence)
{
    statement
}

for(i in 1:5)
{
  print ("Hello")
}

for (val in vector_r) {
    if(val %% 2 == 0)  count = count+1
}

for (i in 1:ncol(bank)) {
  bank[, i] <- factor(bank[, i]) 
}

for (i in 1:nrow(bank))
{  
       person <- bank[i, ]
       person
       
       if(person$marital == "married")
       {
         if(person$housing == "yes" | (!is.na(person$salary) & person$salary) > 60000)
         {
           bank[i,"my_decision"] <- "yes"
         }
         else
         {
           bank[i,"my_decision"] <- "no"
         }
       } else if(person$marital == "single")
       {
         if(person$education == "tertiary" & !is.na(person$salary) & person$salary > 40000)
         {
           bank[i,"my_decision"] <- "yes"
         }
         else
         {
           bank[i,"my_decision"] <- "no"
         }
       }
}

for (val in r_vector) {
    if (val == 3){
        break
    }
    print(val)
}

while loop syntax:
while (test_expression)
{
   statement
}

while (i < 6) {
   print(i)
   i = i+1
}

while(runif(1) < 0.95)
{
  message("Inside the ", i, "th iteration of a while loop.")
  flush.console()
  i <- i + 1
}

repeat loop syntax:
repeat {
   statement
}

repeat loop will always have break statement.

repeat {
   print(x)
   x = x+1
   if (x == 6){
       break
   }
}

break( ) # exits from the innermost loop
next( ) # skips current iteration and starts next iteration

Related Articles:  if else, ifelse function, switch, in R   R Interview Questions


No comments:

Post a Comment