New functions this week: apply

apply(X, MARGIN, FUN)
  • X - an array, including a matrix.
  • MARGIN - 1 indicates rows, 2 indicates columns
  • FUN - the function to be applied

Example: apply

# Generate random matrix
x = as.matrix(data.frame(sample.int(10, 5),
                         sample.int(10, 5),
                         sample.int(10, 5)))
colnames(x) = c("sample1","sample2","sample3")
x
     sample1 sample2 sample3
[1,]      10       2       8
[2,]       7       4       2
[3,]       4       9       1
[4,]       2       5      10
[5,]       6      10       5

Example: apply (rows)

x
     sample1 sample2 sample3
[1,]      10       2       8
[2,]       7       4       2
[3,]       4       9       1
[4,]       2       5      10
[5,]       6      10       5
apply(x, 1, max)
[1] 10  7  9 10 10

Example: apply (columns)

x
     sample1 sample2 sample3
[1,]      10       2       8
[2,]       7       4       2
[3,]       4       9       1
[4,]       2       5      10
[5,]       6      10       5
apply(x, 2, min)
sample1 sample2 sample3 
      2       2       1 

Making your own function

function (arguments) {use arguments to return result}

sumx3 = function(x) {x+3}
sumx3(2)
[1] 5

Making your own function

x
     sample1 sample2 sample3
[1,]      10       2       8
[2,]       7       4       2
[3,]       4       9       1
[4,]       2       5      10
[5,]       6      10       5
locate10 = function(x) {which(x == 10)}
locate10(x)
[1]  1 10 14

Combine your own function with apply

locate10 = function(x) {which(x == 10)}
locate10(x)
[1]  1 10 14
apply(x, 2, locate10)
sample1 sample2 sample3 
      1       5       4