How to select a column of a matrix by column name in R?


When we create a matrix in R, its column names are not defined but we can name them or might import a matrix that might have column names. If the column names are not defined then we simply use column numbers to extract the columns but if we have column names then we can select the column by name as well as its name.

Example1

M1 <-matrix(1:25,nrow=5)
M1

Output

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

Example

colnames(M1) <-c("C1","C2","C3","C4","C5")
M1

Output

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

Example

M1[,"C1"]

Output

[1] 1 2 3 4 5

Example

M1[,"C2"]

Output

[1] 6 7 8 9 10

Example

M1[,"C4"]
[1] 16 17 18 19 20

Example

M1[,"C5"]

Output

[1] 21 22 23 24 25

Example2

M2 <-matrix(sample(1:100,36),nrow=6)
M2

Output

[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 97 53 27 60 13 8
[2,] 41 98 38 73 74 57
[3,] 65 54 15 49 9 5
[4,] 46 87 100 19 94 62
[5,] 6 23 91 45 34 32
[6,] 71 51 26 85 29

Example

colnames(M2) <-c("Rate","Percentage","Class","Group","ID","Section")
M2

Output

Rate Percentage Class Group ID Section
[1,] 97 53 27 60 13 8
[2,] 41 98 38 73 74 57
[3,] 65 54 15 49 9 5
[4,] 46 87 100 19 94 62
[5,] 6 23 91 45 34 32
[6,] 71 51 26 85 29 70

Example

M2[,"Rate"]

Output

[1] 97 41 65 46 6 71

Example

M2[,"Percentage"]

Output

[1] 53 98 54 87 23 51

Example

M2[,"Class"]

Output

[1] 27 38 15 100 91 26

Example

M2[,"Group"]

Output

[1] 60 73 49 19 45 85

Example

M2[,"ID"]

Output

[1] 13 74 9 94 34 29

Example

M2[,"Section"]

Output

[1] 8 57 5 62 32 70

Example3

M3 <-matrix(1:100,nrow=10)
colnames(M3) <-c("Var1","Var2","Var3","Var4","Var5","Var6","Var7","Var8","Var9","Var10")
M3

Output

Var1 Var2 Var3 Var4 Var5 Var6 Var7 Var8 Var9 Var10
[1,] 1 11 21 31 41 51 61 71 81 91
[2,] 2 12 22 32 42 52 62 72 82 92
[3,] 3 13 23 33 43 53 63 73 83 93
[4,] 4 14 24 34 44 54 64 74 84 94
[5,] 5 15 25 35 45 55 65 75 85 95
[6,] 6 16 26 36 46 56 66 76 86 96
[7,] 7 17 27 37 47 57 67 77 87 97
[8,] 8 18 28 38 48 58 68 78 88 98
[9,] 9 19 29 39 49 59 69 79 89 99
[10,] 10 20 30 40 50 60 70 80 90 100

Example

M3[,"Var1"]

Output

[1] 1 2 3 4 5 6 7 8 9 10

Example

M3[,"Var5"]

Output

[1] 41 42 43 44 45 46 47 48 49 50

Example

M3[,"Var7"]

Output

[1] 61 62 63 64 65 66 67 68 69 70

Example

M3[,"Var9"]

Output

[1] 81 82 83 84 85 86 87 88 89 90

Updated on: 24-Aug-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements