R - Control Structure

  • If... else...
    • Example: print msg if your age is under 19
    •  > if(age <19){  
       +   print("you are not adult")  
       + } else {  
       +   print("you are adult")  
       + }  
       [1] "you are not adult"  
      
  • For loop
    • Takes an iterator variable by successive values from a vector. 
    • Example: loop a vector
    •  > x <- c("a","B","c") 
       > for(i in x){  
       +   print(i)  
       + }  
       [1] "a"  
       [1] "B"  
       [1] "c"  
      
    • Use seq_along() function for looping
    •  > for(i in seq_along(x)){  # seq_along returns integer vector 1:3
       +   print(x[i])  
       + }  
       [1] "a"  
       [1] "B"  
       [1] "c"  
      
    • Loop for matrix using seq_len()
    •  > x <- matrix(1:4,2,2)  
       > for(i in seq_len(nrow(x))){  
       +   for(j in seq_len(ncol(x))){  
       +     print(x[i,j])  
       +   }  
       + }  
       [1] 1  
       [1] 3  
       [1] 2  
       [1] 4  
      # difference between seq_len() and seq_along()
       > nrow(x)  
       [1] 2  
       > seq_len(nrow(x))  
       [1] 1 2  
       > seq_along(nrow(x))  
       [1] 1  
      
  • While loop
    • Loops while the testing condition is true
    •  > while(age <19){  
       +   print("you can't enter the club")  
       +   age <- age+1  
       + }  
       [1] "you can't enter the club"  
       [1] "you can't enter the club"  
      
  • next keyword
    • Skip an iteration of a loop 
    •  > for(i in 1:4){  
       +   if(i<2){  
       +     next  # skip to next iteration
       +   }  
       +   print("Hello")  
       + }  
       [1] "Hello"  
       [1] "Hello"  
       [1] "Hello"  
      

No comments:

Post a Comment