Matrix Function in R – apply() and sapply() Functions in R
1. Matrix Function in R
So, in our previous blog of R, we have discussed What is R Matrix in detail. Today, we are going to cover the functions that are applied to the matrices in R i.e. apply() and sapply() function. Moreover, in this R tutorial, we will deeply understand what is Matrix Function in R, what is R apply(), what is sapply(). Also, we will see how to use these functions of the R matrix with the help of examples.
So, let’s start exploring Matrix Functions in R.
2. What is R Matrix and Matrix Function in R?
First of all, we will discuss what exactly matrices are. A matrix is a two-dimensional rectangular data set. Thus it can create using vector input to the matrix function. Also, a matrix is a collection of numbers arranged into a fixed number of rows and columns. Usually, the numbers are the real numbers. We reproduce a memory representation of the matrix in R with the matrix function. Hence, the data elements must be of the same basic type. Matrices functions are those functions which we use in matrices.
There are two types of Matrix Function in R:
We have discussed in above paragraph about R matrix. Now let’s proceed to detail understanding of the types of Matrix Function in R.
3. What is apply() function in R?
Let’s now understand the R apply() function and its usage with examples.
i. apply() function in R
It applies Functions over Array margins. It returns a vector or array or list of values obtained by applying a function to margins of an array or matrix.
Keywords – array, iteration
Usage – apply(X, MARGIN, FUN, …)
Arguments – The arguments to the apply function in R are explained below-
- X – an array, including a matrix
- … – optional arguments to FUN
- FUN – The function to apply: see ‘Details’
- MARGIN – Functions will apply on subscripts in a vector.
For example, a matrix 1 indicates rows, 2 indicates columns, c(1, 2) indicates rows and columns. In this X has named dimnames, it can be a character vector selecting dimension names.
ii. The apply() family
Apply functions are a family of functions in base R. which allow us to perform an action on many chunks of data. An apply function is a loop, but run faster than loops and often must less code. So, there are many different apply() functions.
The called function could be:
- There is some aggregating function. They include meaning, or the sum(includes return a number or scalar);
- Other transforming or subsetting functions.
- There are some vectorized functions. They return more complex structures like lists, vectors, matrices, and arrays.
- We can perform operations with very few lines of code in apply().
iii. How to use apply() function in R?
So, let us start with apply(), which operates on arrays:
a. apply function in R Examples
my.matrx is a matrix with 1-5 in column 1, 6-10 in column 2, and 11-15 in column 3. my.matrx is being used to show some of the basic uses for the apply function.
my.matrx <- matrix(c(1:5, 6:10, 11:15), nrow = 5, ncol = 3) my.matrx ## [,1] [,2] [,3] ## [1,] 1 6 11 ## [2,] 2 7 12 ## [3,] 3 8 13 ## [4,] 4 9 14 ## [5,] 5 10 15
Example 1: Using apply to find row sums
What If we want to summarize the data in matrix m by finding the sum of each row? The arguments are X = m, MARGIN = 1 (for row), and FUN = sum
apply(my.matrx, 1, sum) ##  18 21 24 27 30
It returned a vector containing the sums for each row.
Example 2: Creating a function in the arguments
What if we want to be able to find how many data points (n) are in each column of m? .we are using columns, MARGIN = 2, thus, we can use length function to do this.
apply(my.matrx, 2, length) ##  5 5 5
There isn’t a function in R to find n-1 for each column. So if we want to, we have to create our own Function. If the function is simple, you can create it right inside the arguments for applying. In the arguments, I created a function that returns length – 1.
apply(my.matrx, 2, function (x) length(x)-1) ##  4 4 4
As we have seen, the function returned a vector of n-1 for each column.
Example 3: Transforming data
So, in the previous examples, we used apply to summarize over to a row or column. We can also use apply to repeat a function on cells within a matrix. Now, in this example, we will learn how to use apply a function to transform the values in each cell. Give more attention to the MARGIN argument
my.matrx2 <- apply(my.matrx,1:2, function(x) x+3). my.matrx2 ## [,1] [,2] [,3] ## [1,] 4 9 14 ## [2,] 5 10 15 ## [3,] 6 11 16 ## [4,] 7 12 17 ## [5,] 8 13 18
Example 4: Vectors?
So, in previous examples, we have learned several ways to use the apply function on a matrix. But what if we want to loop through a vector instead? Will the apply function work?
vec <- c(1:5) vec ##  1 2 3 4 5 apply(vec, 1, sum)
When we will run this function it will return the error: Error in apply(v, 1, sum): dim(X) must have a positive length. As we can see, this didn’t work because apply was expecting the data to have at least two dimensions. If we are using data in a vector we need to use lapply, sapply, or vapply instead.
Any doubt yet in Matrix Function in R? Please Comment?
4. What is sapply() function in R?
A Dimension Preserving Variant of “sapply” and “lapply”
sapply is a user-friendly version. It is a wrapper of lapply. By default, sapply returns a vector, matrix or an array.
Keywords – Misc, utilities
Usage – Sapply(X, FUN, …, simplify = TRUE, USE.NAMES = TRUE)
Lapply(X, FUN, …)
Arguments – The arguments used in the sapply() function are discussed below-
- X – It is a vector or list to call sapply.
- FUN – A function.
- … – Optional arguments to FUN.
- simplify – It is a logical value which defines whether a result is been simplified to a vector or matrix if possible?
- USE.NAMES – Logical; if TRUE and if X is a character, use X as names for the result unless it had names already.
i. How to use sapply() function in R?
sapply() function applies a function to margins of an array or matrix.
Usage – sapply(x, func, …, simplify = TRUE, USE.NAMES = TRUE)
sapply function in R Example:
>BOD #R built-in dataset, Biochemical Oxygen Demand Time demand 1 8.0 2 10.0 3 19.0
Sum up for each row:
> sapply(BOD, sum) Time demand 6 27
Multipy all values by 10:
> sapply(BOD,function(x) 10 * x) Time demand [1,] 10 80 [2,] 20 100 [3,] 30 190
Used for array, margin set to 1:
> x <- array(1:9) > sapply(x,function(x) x * 10)  10 20 30 40 50 60 70 80 90
Two dimension array, the margin can be 1 or 2:
> x <- array(1:9,c(3,3)) > x [,1] [,2] [,3] [1,] 1 4 7 [2,] 2 5 8 [3,] 3 6 9 > sapply(x,function(x) x * 10)  10 20 30 40 50 60 70 80 90
sapply: returns a vector, matrix or an array
# sapply: returns a vector, an array or matrix
sapply(c(1:3), function(x) x^2)  1 4 9
So, this was all on Matrix function in R. Hope you like our explanation.
Hence, we have studied in detail about Matrix Function in R. Also, we discussed the most promising usages, examples and how the function is applied over datatypes have its ability to learn. Moreover, in this tutorial we have discussed in detail about two major Matrix Function in R: apply() and sapply() with its usage and examples. Hence, the information which we have discussed in this tutorial is sufficient enough to learn matrices and its functions in R.
Still, if you have any query or suggestions related to this Matrix Function in R, feel free to share with us in the comment section.