How to remove a row from matrix in R by using its name?


To remove a row from matrix in R by using its name, we can follow the below steps −

  • First of all, create a matrix.

  • Then, add names to rows of the matrix.

  • After that, subset the matrix by deselecting the desired row with negation and single square brackets for subsetting.

Example

Create the matrix

Let’s create a matrix as shown below −

M<-matrix(rpois(100,5),ncol=4)
M

Output

On executing, the above script generates the below output(this output will vary on your system due to randomization) −

    [,1] [,2] [,3] [,4]
[1,]  6   0    5    7
[2,]  2   6    8    7
[3,]  9   6    5    5
[4,]  4   8    3    8
[5,]  6   4    2    9
[6,]  3   4    4    9
[7,]  7   6    5    6
[8,]  4   5    7    2
[9,]  7   5    9    8
[10,] 5   7    8    5
[11,] 7   9    5    8
[12,] 9   2    4    8
[13,] 7   2    4    5
[14,] 2   6    8    4
[15,] 8   4    7    7
[16,] 5   3    3    2
[17,] 6   5    5    5
[18,] 5   7    8    5
[19,] 6   5    5    5
[20,] 2   9    6    4
[21,] 5   3    7    7
[22,] 5   3   12    5
[23,] 8   3    3    5
[24,] 7   3    6    1
[25,] 3   3    5    7

Add the row names

Using rownames function to add the row names to matrix M −

M<-matrix(rpois(100,5),ncol=4)
rownames(M)<-LETTERS[1:25]
M

Output

  [,1] [,2] [,3] [,4]
A  6    0    5    7
B  2    6    8    7
C  9    6    5    5
D  4    8    3    8
E  6    4    2    9
F  3    4    4    9
G  7    6    5    6
H  4    5    7    2
I  7    5    9    8
J  5    7    8    5
K  7    9    5    8
L  9    2    4    8 
M  7    2    4    5
N  2    6    8    4
O  8    4    7    7
P  5    3    3    2
Q  6    5    5    5
R  5    7    8    5
S  6    5    5    5
T  2    9    6    4
U  5    3    7    7
V  5    3   12    5
W  8    3    3    5
X  7    3    6    1
Y  3    3    5    7

Remove the row from matrix using row name

Subset the matrix by deselecting the row A with negation and single square brackets as shown below −

M<-matrix(rpois(100,5),ncol=4)
rownames(M)<-LETTERS[1:25]
M<-M[rownames(M)!="A",]
M

Output

 [,1] [,2] [,3] [,4]
B  2    6    8    7
C  9    6    5    5
D  4    8    3    8
E  6    4    2    9
F  3    4    4    9
G  7    6    5    6
H  4    5    7    2
I  7    5    9    8
J  5    7    8    5
K  7    9    5    8
L  9    2    4    8
M  7    2    4    5
N  2    6    8    4
O  8    4    7    7
P  5    3    3    2
Q  6    5    5    5
R  5    7    8    5
S  6    5    5    5
T  2    9    6    4
U  5    3    7    7
V  5    3   12    5
W  8    3    3    5
X  7    3    6    1
Y  3    3    5    7

Updated on: 16-Nov-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements