Select column which starts with or ends with certain character

Here we can also select columns based on starting and ending characters.

  • starts_with() is used to return the column that starts with the given character.

Syntax:

select(dataframe,starts_with(‘substring’))

Where, dataframe is the input dataframe and substring is the character/string that starts with it

  • ends_with() is used to return the column that ends with the given character.

Syntax:

select(dataframe,ends_with(‘substring’))

where, dataframe is the input dataframe and substring is the character/string that ends with it

Example 1: R program to display columns that starts with a character/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 starts with n
print(select(data1,starts_with('n')))
  
# select column that starts with add
print(select(data1,starts_with('add')))


Output:

Example 2: R program to select column that ends with a given string or character

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 ends with ss
print(select(data1,ends_with('ss')))
  
# select column that ends with d
print(select(data1,ends_with('d')))


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:

Similar Reads

Select column with column name

Here we will use select() method to select column by its name...

Select column(s) by position

...

Select column which contains a value or matches a pattern

...

Select column which starts with or ends with certain character

We can also use the column position and get the column using select() method. Position starts with 1....

Select all columns

...