Exercise 5: R matrix operations

[This article was first published on R programming tutorials and exercises for data science and mathematics, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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.
To leave a comment for the author, please follow the link and comment on their blog: R programming tutorials and exercises for data science and mathematics.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)