Adding And Deleting Rows And Columns on Matrix In R Programming

Adding And Deleting Rows And Columns on Matrix     

    It is possible to add or delete rows and columns to an existing matrix using various functions. Matrices can be modified by adding or deleting rows and columns.

Ø   The types of adding and deleting rows and columns are:

a.         Adding rows to a matrix

b.         Adding columns to a matrix

c.         Deleting rows from a matrix

d.         Deleting columns from a matrix

A. Adding Rows and Columns:

The rbind() function is used to add new rows to a matrix.

The cbind() function is used to add new columns to a matrix.

Syntax for adding rows:                                     rbind(matrix, new_row)

Syntax for adding columns:                              cbind(matrix, new_col)

       Here, matrix is the original matrix to which we want to add a row or a column.

new_row and new_col are vectors that contain the values to be added as a new row or a new column, respectively.

Example:

mat <- matrix(1:9, nrow=3, ncol=3)                                                    # Create a matrix

new_row <- c(10,11,12)                                                                        # Add a row to the matrix

mat <- rbind(mat, new_row)

new_col <- c(4,5,6,7)                                                                              # Add a column to the matrix

mat <- cbind(mat, new_col)

print(mat)                                                                                                  # Print the modified matrix

Output:

     [,1] [,2] [,3] [,4]

[1,]    1    4    7    4

[2,]    2    5    8    5

[3,]    3    6    9    6

[4,]   10   11   12    7

B. Deleting Rows and Columns:

To delete a row or a column from a matrix, we can use the indexing feature in R. The negative index values are used to delete a row or a column.

Syntax for deleting rows: matrix[-row_index, ]

Syntax for deleting columns: matrix[ , -col_index]

Here, row_index and col_index are the indices of the rows or columns that we want to delete.

Example:

mat <- mat[-2, ]                                                    # Delete the second row

mat <- mat[, -3]                                                    # Delete the third column

print(mat)                                                              # Print the modified matrix

Output:

          [,1]      [,2] 

[1,]     1          4    

[2,]     3          6    

[3,]   10       11  

Applying Functions to Matrix Rows and Columns in R Programming

 Applying functions to matrix rows and columns in R programming 

Applying functions to matrix rows and columns in R programming allows us to perform operations on the elements of the matrix along rows or columns. This can be useful for tasks like calculating row or column means, standard deviations, or other summary statistics.

These are the different ways to apply functions to matrix rows and columns in R programming.


One of the most famous and most used features of R is the *apply() family of functions, such as apply(), tapply(), and lapply()etc….


A. Using apply() function: 

The apply() function applies a function to the rows or columns of a matrix.

Syntax:      apply(X, MARGIN, FUN, ...)


Parameters :

X: the matrix or array

MARGIN: 1 for rows and 2 for columns

FUN: the function to be applied

...: additional arguments to the function


B. Using sapply() function: 

The sapply() function is similar to apply() function but it returns a vector instead of a matrix.


Syntax:      sapply(X, FUN, ...)

Parameters :

X: the matrix or array

FUN: the function to be applied

...: additional arguments to the function


C. Using lapply() function: 

The lapply() function applies a function to each element of a list or a matrix. The syntax for lapply() function is as follows:

Syntax:      lapply(X, FUN, ...)


Parameters :

X: the matrix or array

FUN: the function to be applied

...: additional arguments to the function


D. Using rowSums() and colSums() functions: 

The rowSums() function computes the sum of each row of a matrix and returns a vector. The colSums() function computes the sum of each column of a matrix and returns a vector. The syntax for these functions is as follows:

Syntax:      rowSums(x, na.rm = FALSE)

colSums(x, na.rm = FALSE)


Parameters :

x: the matrix or array

na.rm: logical indicating whether missing values should be removed


Example : 

mat <- matrix(1:9, nrow=3, ncol=3)                                             # Create a matrix

colSums <- apply(mat, 2, sum)                                     # Apply the sum function to each column

rowSums <- sapply(mat, sum)        # Apply the sum function to each row and return a vector

# Apply the sqrt function to each element of the matrix and return a matrix

sqrtMat <- matrix(unlist(lapply(mat, sqrt)), nrow=3, ncol=3)

rowSums <- rowSums(mat)                                          # Compute the sum of each row

colSums <- colSums(mat)                                                          # Compute the sum of each column

cat("Original matrix:\n")                                                # Print the results

print(mat)

cat("Column sums:\n")

print(colSums)

cat("Row sums:\n")

print(rowSums)

cat("Square root of matrix:\n")

print(sqrtMat)

Output : 

      [,1] [,2] [,3]

[1,]   1    4    7  

[2,]   2    5    8  

[3,]   3    6    9  

rowSums: 12 15 18

colSums: 6 15 24

sqrtMat: 

         [,1]     [,2]     [,3]

[1,] 1.000000 2.000000 2.645751

[2,] 1.414214 2.236068 2.828427

[3,] 1.732051 2.449490 3.000000

Matrix Operations In R Programming

 

Matrices in R programming are used for storing homogeneous data that can be accessed and manipulated easily. Matrix operations are used for performing various arithmetic and logical operations on matrices in R.


Ø   The common matrix operations:

l   Addition and Subtraction: Matrices can be added and subtracted using the + and - operators. The matrices should have the same dimensions for addition and subtraction.

Syntax:      mat1 + mat2            &         mat1 - mat2


l   Multiplication: Matrices can be multiplied using the %*% operator. The number of columns in the first matrix should be equal to the number of rows in the second matrix.

Syntax:      mat1 %*% mat2


l   Transpose: The transpose of a matrix can be obtained using the t() function.

Syntax:      t(mat)


l   Inverse: The inverse of a matrix can be obtained using the solve() function. The matrix should be a square matrix and should be invertible.

Syntax:      solve(mat)


Determinant: The determinant of a matrix can be obtained using the det() function. The matrix should be a square mat

Syntax:      det(mat)


Eigenvalues and Eigenvectors: The eigenvalues and eigenvectors of a matrix can be obtained using the eigen() function.

Syntax:       eigen(mat)


Diagonal: The diagonal elements of a matrix can be obtained using the diag() function.

Syntax:       diag(mat)


Row and Column Operations: Rows and columns of a matrix can be selected and operated upon using the [] operator.

Syntax:

mat[row,] # Row Operations

mat[,col] # Column Operations


Example:

mat1 <- matrix(1:6, nrow=2)                            # Create two matrices

mat2 <- matrix(7:12, nrow=2)

mat3 <- mat1 + mat2                                          # Addition of two matrices

cat("Addition of two matrices:\n", mat3, "\n")

mat4 <- mat1 - mat2                                           # Addition of two matrices

cat("Subtraction of two matrices:\n", mat4, "\n")

mat5 <- mat1 %*% mat2                                               # Multiplication of two matrices

cat("Multiplication of two matrices:\n", mat5, "\n")

mat6 <- t(mat1)                                                    # Transpose of a matrix

cat("Transpose of a matrix:\n", mat6, "\n")

mat7 <- solve(mat1)                                            # Inverse of a matrix

cat("Inverse of a matrix:\n", mat7, "\n")

mat8 <- det(mat1)                                                           # Determinant of a matrix

cat("Determinant of a matrix:\n", mat8, "\n")

mat9 <- eigen(mat1)                                           # Eigenvalues and eigenvectors of a matrix

cat("Eigenvalues of a matrix:\n", mat9$values, "\n")

cat("Eigenvectors of a matrix:\n", mat9$vectors, "\n")

mat10 <- diag(mat1)                                           # Diagonal of a matrix

cat("Diagonal of a matrix:\n", mat10, "\n")

mat11 <- mat1[1,]                                                           # Select a row of a matrix

cat("Selected row of a matrix:\n", mat11, "\n")

mat12 <- mat1[,2]                                                           # Select a column of a matrix

cat("Selected column of a matrix:\n", mat12, "\n")


Output : 

Addition of two matrices:

      [,1] [,2] [,3]

[1,]    8   10   12

[2,]   14   16   18 

Subtraction of two matrices:

     [,1] [,2] [,3]

[1,]   -6   -6   -6

[2,]   -6   -6   -6 

Multiplication of two matrices:

     [,1] [,2] [,3]

[1,]   58   64   70

[2,]  139  154  169 

Transpose of a matrix:

     [,1] [,2] [,3]

[1,]    1    3    5

[2,]    2    4    6 

Inverse of a matrix:

         [,1]     [,2]

[1,] -1.66667  1.16667

[2,]  1.33333 -0.66667 

Determinant of a matrix:

[1] -2 

Eigenvalues of a matrix:

[1] -0.3722813  8.3722813 

Eigenvectors of a matrix:

          [,1]      [,2]

[1,] -0.824564 0.4159736

[2,]  0.565767 0.9093767

Diagonal of a matrix:

[1] 1 4

Selected row of a matrix:

[1] 1 3 5

Selected column of a matrix:

[1] 2 4

Matrices In r Programming

 

In R programming, a matrix is a two-dimensional data structure that contains elements of the same data type. Matrices are useful for storing and manipulating data that can be represented in rows and columns. In R, matrices can be created using the matrix() function.


Syntax:

matrix(data = NA, nrow = 1, ncol = 1, byrow = FALSE, dimnames = NULL)


Parameters:

l    data: The input vector that will be used to create the matrix.

l    nrow: The number of rows in the matrix.

l    ncol: The number of columns in the matrix.

l    byrow: A logical value indicating whether the matrix should be filled by rows or columns.

l    dimnames: A list with names for the rows and columns.


Ø   Types of Matrices

There are different types of matrices in R, which include:

l    Numeric matrix: A matrix that contains numeric values.

l    Character matrix: A matrix that contains character values.

l    Logical matrix: A matrix that contains logical values (TRUE or FALSE).

l    Integer matrix: A matrix that contains integer values.


Ø   Accessing Elements of a Matrix:

In R, matrix elements can be accessed using row and column indices. The index of the first element in a matrix is [1, 1].

# create a matrix

m <- matrix(c(1, 2, 3, 4, 5, 6), nrow = 2)

# access matrix elements

m[1, 1]  # returns 1

m[1, 2]  # returns 3

m[2, 1]  # returns 2

m[2, 2]  # returns 4


Ø   Modifying Elements of a Matrix:

Matrix elements can be modified using the assignment operator (<-).

# modify matrix elements

m[1, 1] <- 10

m[2, 2] <- 20

# print the modified matrix

m

Output:

           [,1]     [,2]

[1,]   10      3

[2,]   2        20


Ø   Concatenating Matrices:

Matrices can be concatenated by rows or columns using the cbind() and rbind() functions, respectively.

# create two matrices

m1 <- matrix(c(1, 2, 3, 4), nrow = 2)

m2 <- matrix(c(5, 6, 7, 8), nrow = 2)

# concatenate matrices by columns

cbind(m1, m2)

# concatenate matrices by rows

rbind(m1, m2)


Output:

# concatenating matrices by columns

     [,1] [,2] [,3] [,4]

[1,]    1    3    5    7

[2,]    2    4    6    8

# concatenating matrices by rows

     [,1] [,2]

[1,]    1    2

[2,]    3    4

[3,]    5    6

[4,]    7    8

R Programming Language

Data Analytics and the key concepts and techniques of R language

Data Analytics  Data analytics is the process of examining, cleaning, transforming, and modeling data to extract useful information and insi...