Select column which contains a value or matches a pattern
Here, we will display the column values based on values or pattern present in the column
Method 1: Using contains()
Display the column that contains the given sub string
Syntax:
select(dataframe,contains(‘sub_string’))
Here, dataframe is the input dataframe and sub_string is the string present in the column name
Example: R program to select column based on substring
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' )) # select column that contains am print ( select (data1, contains ( 'am' ))) # select column that contains d print ( select (data1, contains ( 'd' ))) # select column that contains dd print ( select (data1, contains ( 'dd' ))) |
Output:
Method 2: Using matches()
It will check and display the column that contains the given sub string
select(dataframe,matches(‘sub_string’))
Here, dataframe is the input dataframe and sub_string is the string present in the column name
Example: R program to select column based on substring
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' )) # select column that matches with am print ( select (data1, matches ( 'am' ))) # select column that matches with d print ( select (data1, matches ( 'd' ))) # select column that matches with dd print ( select (data1, matches ( 'dd' ))) |
Output:
Select variables (columns) in R using Dplyr
In this article, we are going to select variables or columns in R programming language using dplyr library.
Dataset in use: