- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to remove multiple columns from matrix in R by using their names?
To remove multiple columns from matrix in R by using their names, we can follow the below steps −
First of all, create a matrix.
Then, add names to columns of the matrix.
After that, subset the matrix by deselecting the desired columns 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,] 3 5 6 6 [2,] 4 1 3 5 [3,] 5 6 3 3 [4,] 4 6 8 6 [5,] 5 9 2 5 [6,] 1 6 7 5 [7,] 7 1 5 6 [8,] 5 6 4 6 [9,] 1 5 11 7 [10,] 3 3 6 4 [11,] 3 5 8 5 [12,] 1 10 3 1 [13,] 7 10 3 4 [14,] 5 6 4 5 [15,] 11 6 13 5 [16,] 8 4 6 1 [17,] 1 3 5 5 [18,] 2 7 7 7 [19,] 5 6 2 8 [20,] 6 4 6 7 [21,] 5 7 3 10 [22,] 4 5 1 2 [23,] 6 2 4 3 [24,] 4 5 4 4 [25,] 3 11 4 3
Add the column names
Using colnames function to add the column names to matrix M −
M<-matrix(rpois(100,5),ncol=4) colnames(M)<-c("Grp1","Grp2","Grp3","Grp4") M
Output
Grp1 Grp2 Grp3 Grp4 [1,] 3 5 6 6 [2,] 4 1 3 5 [3,] 5 6 3 3 [4,] 4 6 8 6 [5,] 5 9 2 5 [6,] 1 6 7 5 [7,] 7 1 5 6 [8,] 5 6 4 6 [9,] 1 5 11 7 [10,] 3 3 6 4 [11,] 3 5 8 5 [12,] 1 10 3 1 [13,] 7 10 3 4 [14,] 5 6 4 5 [15,] 11 6 13 5 [16,] 8 4 6 1 [17,] 1 3 5 5 [18,] 2 7 7 7 [19,] 5 6 2 8 [20,] 6 4 6 7 [21,] 5 7 3 10 [22,] 4 5 1 2 [23,] 6 2 4 3 [24,] 4 5 4 4 [25,] 3 11 4 3
- Related Articles
- How to aggregate matrix columns by row names in R?
- How to remove duplicate columns from a matrix in R?
- How to remove the row names or column names from a matrix in R?
- How to remove a column from matrix in R by using its name?
- How to remove a row from matrix in R by using its name?
- How to combine multiple columns into one in R data frame without using column names?
- How to remove names from a named vector in R?
- How to find the column names and row names from a matrix in R?
- How to remove column names from an R data frame?
- How to remove list elements by their name in R?
- How to delete columns by their name in data.table in R?
- How to convert a matrix to a data frame with column names and row names as new columns in R?
- How to divide matrix rows by number of columns in R?
- How to remove multiple rows from an R data frame using dplyr package?
- How to remove rows in an R data frame using row names?

Advertisements