2 min read

Exercise 5: R matrix operations

Find a function FUN that leads to the following output:

a <- matrix(1:36, nrow = 6)
b <- matrix(1:25, nrow = 5)
a
##      [,1] [,2] [,3] [,4] [,5] [,6]
## [1,]    1    7   13   19   25   31
## [2,]    2    8   14   20   26   32
## [3,]    3    9   15   21   27   33
## [4,]    4   10   16   22   28   34
## [5,]    5   11   17   23   29   35
## [6,]    6   12   18   24   30   36
FUN(a)
## [1] 16 17 18 19 20 21
b
##      [,1] [,2] [,3] [,4] [,5]
## [1,]    1    6   11   16   21
## [2,]    2    7   12   17   22
## [3,]    3    8   13   18   23
## [4,]    4    9   14   19   24
## [5,]    5   10   15   20   25
FUN(b)
## [1] 11 12 13 14 15

Hint: aim to keep the answer simple. The main logic of the function can often be summarized in a single line of R code.

Answer: click to reveal

We can write the function as follows:

  FUN <- function(x) {
    return(apply(x, MARGIN = 1, FUN = median))
  }
This function computes the median for each row of the input matrix.

For a full collection of R programming tutorials and exercises visit my website at codeRtime.org and the codeRtime YouTube channel.