i

R Programming Complete Tutorial

R Matrix Operations

In this section, first, we will do the arithmetic operation, then transpose operation, then we combine the matrices, and finally, we discuss on apply() function.

Arithmetic Operation:

Matrix follows all the basic arithmetic rules, and it will be element-wise. Suppose in the case of the first example, matrix1 [1, 1] =3, will be added to matrix2 [1, 1] =5 and generate result 8. It will continue for all the elements.

Transpose of a Matrix:

Transpose of a matrix formed by swapping the rows into columns and vice versa.

Matrices Combination:

To combine two matrices, we use two special functions cbind() and rbind(). Cbind() marge two matrices column-wise and rbind() combines them row-wise.

apply() function syntax:

Apply function reduces the number of codes and complexity in R programming. We can construct an apply function using a matrix, a margin, and FUN. If we set 1 in the margin, it will only work for rows, and option 2 is for columns. We can even choose both of them. In FUN, we use a function like a max, sum, etc.

Example of apply() function:

We have already constructed a matrix Matrix2 with 3 columns and 5 rows. Now, if we use the function apply (Matrix2, 1, sum), it will add all the elements row-wise. For row1, it will add all the elements (10+110+210=330) and return 330. It will return 5 results for 5 rows. If we use apply (Matrix2, 2, sum), it will return 3 results combining all the elements of the same column.