How to filter single column of a matrix with column name in R?


To filter a single column of a matrix in R if the matrix has column names, we can simply use single square brackets but this will result in a vector without the column name. If we want to use the column name then column name or column number needs to be passed with drop=FALSE argument as shown in the below examples.

Example1

Live Demo

> M1<-matrix(sample(0:1,80,replace=TRUE),ncol=4)
> colnames(M1)<-c("V1","V2","V3","V4")
> M1

Output

      V1 V2 V3 V4
[1,]  0  0  1  0
[2,]  1  1  1  1
[3,]  0  0  0  0
[4,]  0  1  1  0
[5,]  1  1  1  1
[6,]  0  1  1  0
[7,]  0  1  0  1
[8,]  1  1  0  1
[9,]  1  1  0  1
[10,] 0  0  1  0
[11,] 0  0  0  1
[12,] 0  1  0  0
[13,] 0  0  0  0
[14,] 1  0  0  0
[15,] 0  1  0  1
[16,] 0  0  1  0
[17,] 1  1  1  1
[18,] 1  0  1  1
[19,] 1  0  1  1
[20,] 0  0  0  0

Extracting column V1 from M1 −

> M1[,"V1",drop = FALSE]

Output

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

Example2

Live Demo

> M2<-matrix(sample(c("Yes","No"),40,replace = TRUE),ncol=2)
> colnames(M2)<-c("Binary1","Binary2")
> M2

Output

    Binary1 Binary2
[1,]  "Yes" "Yes"
[2,]  "Yes" "No"
[3,]  "Yes" "No"
[4,]  "Yes" "Yes"
[5,]  "Yes" "Yes"
[6,]  "No"  "No"
[7,]  "Yes" "Yes"
[8,]  "No"  "Yes"
[9,]  "No"  "No"
[10,] "Yes" "Yes"
[11,] "Yes" "Yes"
[12,] "Yes" "No"
[13,] "Yes" "No"
[14,] "No"  "Yes"
[15,] "No"  "Yes"
[16,] "Yes" "Yes"
[17,] "No"  "Yes"
[18,] "Yes" "Yes"
[19,] "Yes" "Yes"
[20,] "No"  "No"

Extracting column Binary2 from M2 −

> M2[,"Binary2",drop = FALSE]

Output

     Binary2
[1,]  "Yes"
[2,]  "No"
[3,]  "No"
[4,]  "Yes"
[5,]  "Yes"
[6,]  "No"
[7,]  "Yes"
[8,]  "Yes"
[9,]  "No"
[10,] "Yes"
[11,] "Yes"
[12,] "No"
[13,] "No"
[14,] "Yes"
[15,] "Yes"
[16,] "Yes"
[17,] "Yes"
[18,] "Yes"
[19,] "Yes"
[20,] "No"

Updated on: 04-Mar-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements