Author: Team BioSakshat

Last update: June 2017

Copyright © 2017 BioSakshat, Inc. All rights reserved.

apply()

# Consider a hypothetical gene expression dataset
# Row: 30 Genes
# Coulmn: Gene expression measured for 4 consecutive days. D1 to D4
# Values: between -1, 1
exp= matrix(rnorm(120), nrow=30)
rownames(exp)=paste("G", 1:nrow(exp),sep="");
colnames(exp)=paste("C", 1:ncol(exp),sep="");
head(exp);
##            C1         C2         C3          C4
## G1 -0.8577631 -0.8751164 -1.1068473  1.05143519
## G2  0.2779501 -0.7762494  0.5736323 -0.13909364
## G3 -1.5633395 -0.1295267 -3.2866602  0.06404329
## G4 -1.1406816 -0.1107565  1.2387336 -1.21430906
## G5 -0.4687612 -1.0406673  0.6127555  0.30693874
## G6  1.2477455  0.1896920  0.1169069  0.43665692
dim(exp);
## [1] 30  4
# apply mean function on every row (margin=1)
apply(exp, MARGIN = 1, FUN = mean);
##           G1           G2           G3           G4           G5 
## -0.447072896 -0.015940148 -1.228870787 -0.306753379 -0.147433552 
##           G6           G7           G8           G9          G10 
##  0.497750329 -0.126707546  0.423302594 -0.478817386  0.224877613 
##          G11          G12          G13          G14          G15 
##  1.565687276 -0.240372255 -0.842461947 -0.366817689  0.312269870 
##          G16          G17          G18          G19          G20 
##  0.596461778 -0.286834969  0.097532228 -0.260290093  0.206142447 
##          G21          G22          G23          G24          G25 
##  0.239885233 -0.115947411 -0.316126493  0.390224934 -0.003662917 
##          G26          G27          G28          G29          G30 
##  0.830990068  0.278790911 -0.733148074 -0.271863185 -1.091746949
# apply mean function on every column (margin=2)
apply(exp, MARGIN = 2, FUN = mean);
##          C1          C2          C3          C4 
## -0.16975258  0.02165388 -0.10947853  0.04198357
# Count how many genes up regulated in each day
apply(exp, MARGIN = 2, FUN = function(x){sum(x>0)});
## C1 C2 C3 C4 
## 13 15 14 16
# Count how many days a gene is down regulated
apply(exp, MARGIN = 1, FUN = function(x){sum(x>0)});
##  G1  G2  G3  G4  G5  G6  G7  G8  G9 G10 G11 G12 G13 G14 G15 G16 G17 G18 
##   1   2   1   1   2   4   3   2   1   2   4   1   0   1   3   3   2   2 
## G19 G20 G21 G22 G23 G24 G25 G26 G27 G28 G29 G30 
##   2   2   3   2   1   3   2   3   2   1   2   0

sapply()

lapply()