Drop column which contains a value or matches a pattern
Let’s see how to remove the column that contains the character/string.
Method 1: Using contains()
Display the column that contains the given substring and then -contains() removes the column that contains the given substring.
Syntax:
select(dataframe,-contains(‘sub_string’))
Here, dataframe is the input dataframe and the sub_string is the string present in the column name that will be removed.
Method 2: Using matches()
Display the column that contains the given substring and then -matches() removes the column that contains the given substring
Syntax:
select(dataframe,-matches(‘sub_string’))
Here, dataframe is the input dataframe and the sub_string is the string present in the column name that will be removed.
Example: R program that removes column using contains() method
R
# load the library library (dplyr) # create dataframe with 3 columns # id,name and address data1= data.frame (id= c (1,2,3,4,5,6,7,1,4,2), name= c ( 'sravan' , 'ojaswi' , 'bobby' , 'gnanesh' , 'rohith' , 'pinkey' , 'dhanush' , 'sravan' , 'gnanesh' , 'ojaswi' ), address= c ( 'hyd' , 'hyd' , 'ponnur' , 'tenali' , 'vijayawada' , 'vijayawada' , 'guntur' , 'hyd' , 'tenali' , 'hyd' )) # remove column that contains na print ( select (data1,- contains ( 'na' ))) # remove column that contains re print ( select (data1,- contains ( 're' ))) |
Output:
Drop multiple columns using Dplyr package in R
In this article, we will discuss how to drop multiple columns using dplyr package in R programming language.
Dataset in use: