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