Author: Team BioSakshat

Last update: June 2017

Copyright © 2017 BioSakshat, Inc. All rights reserved.

Conditional execution

Syntax:
if (expr_1)
{
expr_2
……
……
}else{
expr_3
……
……
}

x=sample(1:50,10);
sum(x);
## [1] 286
if(sum(x)>500)
{
  print("Sum of x is greater than 500");
}else{
  print("Sum of x is less than 500");
}
## [1] "Sum of x is less than 500"

Repetitive execution using for loop

for(i in 5:10)
{
  print(i);
}
## [1] 5
## [1] 6
## [1] 7
## [1] 8
## [1] 9
## [1] 10
for(i in c(10,15,17,16,25))
{
  print(i);
}
## [1] 10
## [1] 15
## [1] 17
## [1] 16
## [1] 25
x=c(10,15,17,16,25);
for(i in x)
{
  print(i);
}
## [1] 10
## [1] 15
## [1] 17
## [1] 16
## [1] 25
x=c(10,15,17,16,25);
for(i in 1:length(x))
{
  print(c(i,x[i]));
}
## [1]  1 10
## [1]  2 15
## [1]  3 17
## [1]  4 16
## [1]  5 25

Store squares of values of above vector in separate vector s using for loop

s = NULL;
for(i in 1:length(x))
{
  s[i] = x[i] ^ 2;
}
x;
## [1] 10 15 17 16 25
s;
## [1] 100 225 289 256 625

Note: Usually we don’t need to use for loop to perform operations on a single vector. The vector s created using above for loop can simply be created using command, s<- x^2. But for loop is very useful to perform operations on multiple columns and rows of a matrix or data frame.

Task

Create a matrix of 5 rows for values 1 to 50. Calculate the means of all rows in a matrix and store them in a vector m.

mat=matrix(sample(1:50, 50, replace = TRUE), nrow=10);
mat;
##       [,1] [,2] [,3] [,4] [,5]
##  [1,]   33   48   30   38   47
##  [2,]   34   25   47   16   11
##  [3,]   23   48    9   26   31
##  [4,]   22   50   15   20   34
##  [5,]   12   21   32    1   30
##  [6,]   24   50   42   12   28
##  [7,]   47    1    9   20   45
##  [8,]   48   29   49   19   24
##  [9,]   34   43    6   12   12
## [10,]   22   22   44   50    2
m=NULL;
for(i in 1:nrow(mat))
{
  m[i] = mean(mat[i,]);
}
m;
##  [1] 39.2 26.6 27.4 28.2 19.2 31.2 24.4 33.8 21.4 28.0